Spaces:
Sleeping
Sleeping
File size: 2,561 Bytes
b358cdb |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
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('"', '"').replace("'", "'")
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 |