import gradio as gr
import openai
import os
from dotenv import load_dotenv
import logging
import datetime
import json
import re
import random
# Set up logging with more detailed configuration
log_dir = "logs"
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_filename = os.path.join(log_dir, f"svg_generator_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.log")
logging.basicConfig(
filename=log_filename,
level=logging.INFO,
format='%(asctime)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s'
)
# Add console handler to see logs in terminal
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler.setFormatter(console_formatter)
logging.getLogger().addHandler(console_handler)
# Load environment variables
load_dotenv()
logging.info("Environment variables loaded")
# Configure OpenAI API
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
logging.error("OPENAI_API_KEY not found in environment variables!")
raise ValueError("OPENAI_API_KEY not found!")
client = openai.OpenAI(api_key=api_key)
logging.info("OpenAI client initialized successfully")
def clean_svg_content(content):
"""Clean and validate SVG content"""
# Remove any leading/trailing whitespace
content = content.strip()
# Log original content for debugging
logging.info(f"Original content starts with: {content[:100]}...")
# Remove XML declaration if present
content = re.sub(r'<\?xml[^>]+\?>\s*', '', content)
# Remove DOCTYPE if present
content = re.sub(r']+>\s*', '', content)
# Remove any comments
content = re.sub(r'\s*', '', content)
# Remove any empty lines
content = '\n'.join(line for line in content.splitlines() if line.strip())
# Log cleaned content
logging.info(f"Cleaned content starts with: {content[:100]}...")
return content
def validate_svg(content):
"""Validate SVG content"""
# Check if content starts with '):
logging.warning("Content doesn't end with closing SVG tag")
return False
return True
def generate_svg(prompt):
"""Generate SVG using the fine-tuned GPT-4 model"""
try:
logging.info(f"Sending request to OpenAI API with prompt: {prompt[:100]}...")
logging.info(f"Using model: ft:gpt-4o-mini-2024-07-18:personal::AyNMN2ax")
response = client.chat.completions.create(
model="ft:gpt-4o-mini-2024-07-18:personal::AyNMN2ax",
messages=[
{"role": "system", "content": """in this add this Create a well-aligned and meaningful SVG generator prompt. Ensure it includes appropriate alignment and content instructions.
# Output Format
The SVG should be generated with structured alignment and include meaningful attributes such as colors, dimensions, and positioning.
# Steps [optional]
1. Define the shapes and their attributes (e.g., circles, rectangles).
2. Set the colors and dimensions.
3. Align the objects to create a cohesive design.
4. Review and adjust for meaningfulness and symmetry.
# Examples [optional]
Example Input:
- Shapes: Circle, Rectangle
- Colors: Blue, Red
- Sizes: 100x100, 50x50
- Positioning: Center
Example Output:
```svg
```
# Notes [optional]
- Ensure the SVG is valid and adheres to SVG standards.
- Ensure in output only generate the svg only in svg you can create comment it's okay
- Consider accessibility aspects such as color contrast.
- Review the design for visual balance and clarity.
- IMPORTANT: Return ONLY the raw SVG code without any markdown formatting or explanations. The response should start with