quick-bright-demo / utils.py
AiCoderv2's picture
Deploy Gradio app with multiple files
b358cdb verified
import os
import requests
from huggingface_hub import InferenceApi
def generate_website_code(prompt, model_choice):
"""Generate website code using Hugging Face inference API"""
try:
# Add context to the prompt for better results
full_prompt = f"""
<!DOCTYPE html>
<html>
<head>
<title>Generated Website</title>
<style>
/* CSS styles */
</style>
</head>
<body>
<!-- HTML content -->
<script>
// JavaScript code
</script>
</body>
</html>
Create a complete, functional website based on this description: {prompt}
Include proper HTML5 structure, responsive CSS styling, and interactive JavaScript.
Respond only with the complete code.
"""
inference = InferenceApi(
repo_id=model_choice,
token=os.getenv("HF_API_TOKEN")
)
response = inference(
inputs=full_prompt,
parameters={
"max_new_tokens": 800,
"temperature": 0.7,
"top_p": 0.9,
"repetition_penalty": 1.2,
"do_sample": True
}
)
if isinstance(response, list) and len(response) > 0:
generated_text = response[0].get("generated_text", "")
# Extract HTML code from response
start_html = generated_text.find("<!DOCTYPE html>")
if start_html != -1:
return generated_text[start_html:]
else:
return generated_text
else:
return f"Error: Unexpected response format\n{str(response)}"
except Exception as e:
return f"Error generating code: {str(e)}"
def preview_website(code):
"""Preview website from HTML code"""
if not code or code.strip() == "":
return "<div style='padding: 20px; text-align: center; font-family: sans-serif;'>Enter code to preview website</div>"
# Sanitize and wrap code in iframe for preview
sanitized_code = code.replace('"', '&quot;').replace("'", "&#39;")
iframe_html = f"""
<div style="border: 1px solid #ddd; border-radius: 4px; overflow: hidden; height: 600px;">
<iframe
srcdoc="{sanitized_code}"
style="width: 100%; height: 100%; border: none;"
sandbox="allow-scripts allow-same-origin">
</iframe>
</div>
"""
return iframe_html