Delete api_clients.py
Browse files- api_clients.py +0 -151
api_clients.py
DELETED
@@ -1,151 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
from typing import Dict, List, Optional, Tuple
|
3 |
-
|
4 |
-
import gradio as gr
|
5 |
-
from huggingface_hub import InferenceClient
|
6 |
-
from tavily import TavilyClient
|
7 |
-
|
8 |
-
from config import (
|
9 |
-
HTML_SYSTEM_PROMPT, GENERIC_SYSTEM_PROMPT, HTML_SYSTEM_PROMPT_WITH_SEARCH,
|
10 |
-
GENERIC_SYSTEM_PROMPT_WITH_SEARCH, FollowUpSystemPrompt
|
11 |
-
)
|
12 |
-
from chat_processing import (
|
13 |
-
history_to_messages, messages_to_history,
|
14 |
-
remove_code_block, apply_search_replace_changes, send_to_sandbox,
|
15 |
-
history_to_chatbot_messages, get_gradio_language
|
16 |
-
)
|
17 |
-
from file_processing import ( # file_processing.py
|
18 |
-
extract_text_from_file, create_multimodal_message,
|
19 |
-
)
|
20 |
-
from web_extraction import extract_website_content, enhance_query_with_search
|
21 |
-
|
22 |
-
# HF Inference Client
|
23 |
-
HF_TOKEN = os.getenv('HF_TOKEN')
|
24 |
-
if not HF_TOKEN:
|
25 |
-
raise RuntimeError("HF_TOKEN environment variable is not set. Please set it to your Hugging Face API token.")
|
26 |
-
|
27 |
-
def get_inference_client(model_id, provider="auto"):
|
28 |
-
"""Return an InferenceClient with provider based on model_id and user selection."""
|
29 |
-
return InferenceClient(
|
30 |
-
provider=provider,
|
31 |
-
api_key=HF_TOKEN,
|
32 |
-
bill_to="huggingface"
|
33 |
-
)
|
34 |
-
|
35 |
-
# Tavily Search Client
|
36 |
-
TAVILY_API_KEY = os.getenv('TAVILY_API_KEY')
|
37 |
-
tavily_client = None
|
38 |
-
if TAVILY_API_KEY:
|
39 |
-
try:
|
40 |
-
tavily_client = TavilyClient(api_key=TAVILY_API_KEY)
|
41 |
-
except Exception as e:
|
42 |
-
print(f"Failed to initialize Tavily client: {e}")
|
43 |
-
tavily_client = None
|
44 |
-
|
45 |
-
async def generation_code(query: Optional[str], image: Optional[gr.Image], file: Optional[str], website_url: Optional[str], _setting: Dict[str, str], _history: Optional[List[Tuple[str, str]]], _current_model: Dict, enable_search: bool = False, language: str = "html", progress=gr.Progress(track_tqdm=True)):
|
46 |
-
if query is None:
|
47 |
-
query = ''
|
48 |
-
if _history is None:
|
49 |
-
_history = []
|
50 |
-
|
51 |
-
# Check if there's existing HTML content in history to determine if this is a modification request
|
52 |
-
has_existing_html = False
|
53 |
-
if _history:
|
54 |
-
# Check the last assistant message for HTML content
|
55 |
-
last_assistant_msg = _history[-1][1] if len(_history) > 0 else ""
|
56 |
-
if '<!DOCTYPE html>' in last_assistant_msg or '<html' in last_assistant_msg:
|
57 |
-
has_existing_html = True
|
58 |
-
progress(0, desc="Initializing...")
|
59 |
-
|
60 |
-
# Choose system prompt based on context
|
61 |
-
if has_existing_html:
|
62 |
-
# Use follow-up prompt for modifying existing HTML
|
63 |
-
system_prompt = FollowUpSystemPrompt
|
64 |
-
else:
|
65 |
-
# Use language-specific prompt
|
66 |
-
if language == "html":
|
67 |
-
system_prompt = HTML_SYSTEM_PROMPT_WITH_SEARCH if enable_search else HTML_SYSTEM_PROMPT
|
68 |
-
else:
|
69 |
-
system_prompt = GENERIC_SYSTEM_PROMPT_WITH_SEARCH.format(language=language) if enable_search else GENERIC_SYSTEM_PROMPT.format(language=language)
|
70 |
-
|
71 |
-
messages = history_to_messages(_history, system_prompt)
|
72 |
-
|
73 |
-
# Extract file text and append to query if file is present
|
74 |
-
file_text = ""
|
75 |
-
progress(0.1, desc="Processing file...")
|
76 |
-
if file:
|
77 |
-
file_text = extract_text_from_file(file)
|
78 |
-
if file_text:
|
79 |
-
file_text = file_text[:5000] # Limit to 5000 chars for prompt size
|
80 |
-
query = f"{query}\n\n[Reference file content below]\n{file_text}"
|
81 |
-
|
82 |
-
progress(0.2, desc="Extracting website content...")
|
83 |
-
# Extract website content and append to query if website URL is present
|
84 |
-
website_text = ""
|
85 |
-
if website_url and website_url.strip():
|
86 |
-
website_text = extract_website_content(website_url.strip())
|
87 |
-
if website_text and not website_text.startswith("Error"):
|
88 |
-
website_text = website_text[:8000] # Limit to 8000 chars for prompt size
|
89 |
-
query = f"{query}\n\n[Website content to redesign below]\n{website_text}"
|
90 |
-
elif website_text.startswith("Error"):
|
91 |
-
# Provide helpful guidance when website extraction fails
|
92 |
-
fallback_guidance = """
|
93 |
-
Since I couldn't extract the website content, please provide additional details about what you'd like to build:
|
94 |
-
1. What type of website is this? (e.g., e-commerce, blog, portfolio, dashboard)
|
95 |
-
2. What are the main features you want?
|
96 |
-
3. What's the target audience?
|
97 |
-
4. Any specific design preferences? (colors, style, layout)
|
98 |
-
This will help me create a better design for you."""
|
99 |
-
query = f"{query}\n\n[Error extracting website: {website_text}]{fallback_guidance}"
|
100 |
-
|
101 |
-
progress(0.4, desc="Performing web search...")
|
102 |
-
# Enhance query with search if enabled
|
103 |
-
enhanced_query = enhance_query_with_search(query, enable_search)
|
104 |
-
|
105 |
-
# Use dynamic client based on selected model
|
106 |
-
client = get_inference_client(_current_model["id"])
|
107 |
-
|
108 |
-
if image is not None:
|
109 |
-
messages.append(create_multimodal_message(enhanced_query, image))
|
110 |
-
else:
|
111 |
-
messages.append({'role': 'user', 'content': enhanced_query})
|
112 |
-
progress(0.5, desc="Generating code with AI model...")
|
113 |
-
try:
|
114 |
-
completion = client.chat.completions.create(
|
115 |
-
model=_current_model["id"], # Corrected this line
|
116 |
-
messages=messages,
|
117 |
-
stream=True,
|
118 |
-
max_tokens=5000
|
119 |
-
)
|
120 |
-
progress(0.6, desc="Streaming response...")
|
121 |
-
content = ""
|
122 |
-
for chunk in completion:
|
123 |
-
if chunk.choices[0].delta.content:
|
124 |
-
content += chunk.choices[0].delta.content
|
125 |
-
clean_code = remove_code_block(content)
|
126 |
-
if has_existing_html:
|
127 |
-
# Fallback: If the model returns a full HTML file, use it directly
|
128 |
-
if not (clean_code.strip().startswith("<!DOCTYPE html>") or clean_code.strip().startswith("<html")):
|
129 |
-
last_html = _history[-1][1] if _history else ""
|
130 |
-
modified_html = apply_search_replace_changes(last_html, clean_code)
|
131 |
-
clean_code = remove_code_block(modified_html)
|
132 |
-
|
133 |
-
yield (
|
134 |
-
gr.update(value=clean_code, language=get_gradio_language(language)),
|
135 |
-
_history,
|
136 |
-
send_to_sandbox(clean_code) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML.</div>",
|
137 |
-
history_to_chatbot_messages(_history)
|
138 |
-
)
|
139 |
-
# Final update
|
140 |
-
_history = messages_to_history(messages + [{'role': 'assistant', 'content': content}])
|
141 |
-
final_code = remove_code_block(content)
|
142 |
-
yield (
|
143 |
-
final_code,
|
144 |
-
_history,
|
145 |
-
send_to_sandbox(final_code),
|
146 |
-
history_to_chatbot_messages(_history),
|
147 |
-
)
|
148 |
-
|
149 |
-
except Exception as e:
|
150 |
-
error_message = f"Error: {str(e)}"
|
151 |
-
yield (error_message, _history, None, history_to_chatbot_messages(_history))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|