Update app.py
Browse files12311 unmodified lines15161718192021222324252688 unmodified lines11511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415557 unmodified lines21321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226319 unmodified lines28328428528628728828910 unmodified lines3003013023033043053068 unmodified lines315316317318319320321689 unmodified lines1011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149122 unmodified lines127212731274127512761277127812791280128112821283import refrom http import HTTPStatusfrom typing import Dict, List, Optional, Tuple11 unmodified linesimport html2textimport jsonimport timeimport osimport gradio as grfrom huggingface_hub import InferenceClientfrom tavily import TavilyClientimport openai# Gradio supported languages for syntax highlightingGRADIO_SUPPORTED_LANGUAGES = [88 unmodified lines# Available modelsAVAILABLE_MODELS = [{"name": "DeepSeek V3","id": "deepseek-ai/DeepSeek-V3-0324","description": "DeepSeek V3 model for code generation", "provider": "deepseek"},{"name": "DeepSeek R1","id": "deepseek-ai/DeepSeek-R1-0528","description": "DeepSeek R1 model for code generation", "provider": "deepseek"},{# "name": "GPT-4o-mini",# "id": "gpt-4o-mini",# "description": "OpenAI GPT-4o-mini model for code generation and general tasks",# "provider": "openai"#}, # Commented out to avoid requiring extra setup for all users#{"name": "Gemini 1.5 Pro","id": "gemini-1.5-pro-latest","description": "Google Gemini 1.5 Pro model for code generation and general tasks", "provider": "gemini"},{"name": "GPT-4o","id": "gpt-4o","description": "OpenAI GPT-4o model for code generation and general tasks", "provider": "openai"},{"name": "Qwen3-235B-A22B","id": "Qwen/Qwen3-235B-A22B","description": "Qwen3-235B-A22B model for code generation and general tasks", "provider": "huggingface"},{"name": "GLM-4.1V-9B-Thinking","id": "THUDM/GLM-4.1V-9B-Thinking","description": "GLM-4.1V-9B-Thinking model for multimodal code generation with image support",}]57 unmodified lines]# HF Inference ClientHF_TOKEN = os.getenv("HF_TOKEN")OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")def get_inference_client(model_id):"""Return an appropriate client based on model_id and configured provider."""model_info = next((m for m in AVAILABLE_MODELS if m["id"] == model_id), None)if not model_info:raise ValueError(f"Model with id '{model_id}' not found.")provider = model_info.get("provider")if provider == "deepseek":if not DEEPSEEK_API_KEY:raise ValueError("DEEPSEEK_API_KEY environment variable not set.")return "deepseek_client" # Return a string placeholder, logic is handled in generation_codeif provider == "groq":return InferenceClient(provider="groq",api_key=HF_TOKEN, # Groq uses HF token as wellbill_to="huggingface" # Assuming billing through HF for Groq)elif provider == "huggingface":if not HF_TOKEN:raise ValueError("HF_TOKEN environment variable not set for Hugging Face models.")return InferenceClient(provider="auto", # Use HF's auto provider for other HF modelsapi_key=HF_TOKEN,bill_to="huggingface")elif provider == "openai":if not OPENAI_API_KEY:raise ValueError("OPENAI_API_KEY environment variable not set.")openai.api_key = OPENAI_API_KEYreturn openaielif provider == "gemini":if not GEMINI_API_KEY:raise ValueError("GEMINI_API_KEY environment variable not set.")import google.generativeai as genaigenai.configure(api_key=GEMINI_API_KEY)return genaielse:raise ValueError(f"Unsupported provider: {provider}")# Type definitionsHistory = List[Tuple[str, str]]19 unmodified linestext_content = ""for item in user_content:if isinstance(item, dict) and item.get("type") == "text":text_content += str(item.get("text", ""))user_content = text_content if text_content else str(user_content)messages.append({'role': 'user', 'content': user_content})10 unmodified linestext_content = ""for item in user_content:if isinstance(item, dict) and item.get("type") == "text":text_content += str(item.get("text", ""))user_content = text_content if text_content else str(user_content)history.append([user_content, r['content']])8 unmodified linestext_content = ""for item in user_msg:if isinstance(item, dict) and item.get("type") == "text":text_content += str(item.get("text", ""))user_msg = text_content if text_content else str(user_msg)messages.append({"role": "user", "content": user_msg})689 unmodified lineselse:messages.append({'role': 'user', 'content': enhanced_query})try:if _current_model["provider"] == "openai":# Use OpenAI clientstream = client.chat.completions.create(model=_current_model["id"],messages=[{"role": m["role"], "content": m["content"]} for m in messages],stream=True,max_tokens=5000,)content = ""for chunk in stream:if chunk.choices[0].delta.content:content += chunk.choices[0].delta.contentclean_code = remove_code_block(content)if has_existing_html:# ... (rest of the modification logic) ...if clean_code.strip().startswith("<!DOCTYPE html>") or clean_code.strip().startswith("<html"):yield {code_output: gr.update(value=clean_code, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),sandbox: send_to_sandbox(clean_code) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",}else:last_html = _history[-1][1] if _history else ""modified_html = apply_search_replace_changes(last_html, clean_code)clean_html = remove_code_block(modified_html)yield {code_output: gr.update(value=clean_html, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),sandbox: send_to_sandbox(clean_html) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",}else:yield {code_output: gr.update(value=clean_code, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),sandbox: send_to_sandbox(clean_code) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",}elif _current_model["provider"] == "gemini":# Use Gemini client (assumes you've adapted the message format)chat = client.GenerativeModel(_current_model["id"]).start_chat(history=[]) # Assuming it uses historyfor message in messages[1:]:if message["role"] == "user":chat.send_message(message["content"])elif message["role"] == "assistant":chat.send_message(message["content"])response = chat.send_message(messages[-1]["content"], stream=True)content = ""for chunk in response:content += chunk.textclean_code = remove_code_block(content)if has_existing_html:# ... (rest of the modification logic) ...if clean_code.strip().startswith("<!DOCTYPE html>") or clean_code.strip().startswith("<html"):yield {code_output: gr.update(value=clean_code, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),sandbox: send_to_sandbox(clean_code) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",}else:last_html = _history[-1][1] if _history else ""modified_html = apply_search_replace_changes(last_html, clean_code)clean_html = remove_code_block(modified_html)yield {code_output: gr.update(value=clean_html, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),sandbox: send_to_sandbox(clean_html) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",}else:yield {code_output: gr.update(value=clean_code, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),sandbox: send_to_sandbox(clean_code) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",}elif _current_model["provider"] == "deepseek":# Use requests to call Deepseek API directlyurl = "https://api.deepseek.com/v1/chat/completions"headers = {"Authorization": f"Bearer {DEEPSEEK_API_KEY}","Content-Type": "application/json"}payload = {"model": _current_model["id"], # Use the full model ID from AVAILABLE_MODELS"messages": [{"role": m["role"], "content": m["content"]} for m in messages],"stream": True,"max_tokens": 5000}response = requests.post(url, headers=headers, json=payload, stream=True)response.raise_for_status()content = ""for line in response.iter_lines():if line:line_str = line.decode('utf-8')if line_str.startswith('data: '):json_data = line_str[6:]if json_data.strip() != '[DONE]':chunk = json.loads(json_data)if chunk['choices'][0]['delta'].get('content'):content += chunk['choices'][0]['delta']['content']clean_code = remove_code_block(content)yield {code_output: gr.update(value=clean_code, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),sandbox: send_to_sandbox(clean_code) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",}else:# Use Hugging Face Inference Client (or Groq) for other modelscompletion = client.chat.completions.create(model=_current_model["id"],messages=messages,stream=True,max_tokens=5000)content = ""for chunk in completion:if chunk.choices[0].delta.content:content += chunk.choices[0].delta.contentclean_code = remove_code_block(content)if has_existing_html:# ... (rest of the modification logic) ...if clean_code.strip().startswith("<!DOCTYPE html>") or clean_code.strip().startswith("<html"):yield {code_output: gr.update(value=clean_code, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),sandbox: send_to_sandbox(clean_code) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",}else:last_html = _history[-1][1] if _history else ""modified_html = apply_search_replace_changes(last_html, clean_code)# Handle response based on whether this is a modification or new generationif has_existing_html:# Fallback: If the model returns a full HTML file, use it directly122 unmodified linesoutputs=input)if not tavily_client:tavily_status = gr.Markdown("⚠️ Web search unavailable. Set TAVILY_API_KEY.", visible=True)else:tavily_status = gr.Markdown("✅ Web search available", visible=True)model_display = gr.Markdown(f"**Model:** {AVAILABLE_MODELS[0]['name']}", visible=True) # Moonshot Kimi-K2def on_model_change(model_name):for m in AVAILABLE_MODELS:if m['name'] == model_name:123411 unmodified lines1617181920212223242588 unmodified lines11411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715857 unmodified lines21621721821922022122222322422522622722822923023119 unmodified lines25125225325425525625710 unmodified lines2682692702712722732748 unmodified lines283284285286287288289689 unmodified lines97998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019122 unmodified lines1142114311441145114611471148114911501151import osimport refrom http import HTTPStatusfrom typing import Dict, List, Optional, Tuple11 unmodified linesimport html2textimport jsonimport timeimport gradio as grfrom huggingface_hub import InferenceClientfrom tavily import TavilyClient# Gradio supported languages for syntax highlightingGRADIO_SUPPORTED_LANGUAGES = [88 unmodified lines# Available modelsAVAILABLE_MODELS = [{"name": "Moonshot Kimi-K2","id": "moonshotai/Kimi-K2-Instruct","description": "Moonshot AI Kimi-K2-Instruct model for code generation and general tasks"},{"name": "DeepSeek V3","id": "deepseek-ai/DeepSeek-V3-0324","description": "DeepSeek V3 model for code generation"},{"name": "DeepSeek R1","id": "deepseek-ai/DeepSeek-R1-0528","description": "DeepSeek R1 model for code generation"},{"name": "ERNIE-4.5-VL","id": "baidu/ERNIE-4.5-VL-424B-A47B-Base-PT","description": "ERNIE-4.5-VL model for multimodal code generation with image support"},{"name": "MiniMax M1","id": "MiniMaxAI/MiniMax-M1-80k","description": "MiniMax M1 model for code generation and general tasks"},{"name": "Qwen3-235B-A22B","id": "Qwen/Qwen3-235B-A22B","description": "Qwen3-235B-A22B model for code generation and general tasks"},{"name": "SmolLM3-3B","id": "HuggingFaceTB/SmolLM3-3B","description": "SmolLM3-3B model for code generation and general tasks"},{"name": "GLM-4.1V-9B-Thinking","id": "THUDM/GLM-4.1V-9B-Thinking","description": "GLM-4.1V-9B-Thinking model for multimodal code generation with image support"}]57 unmodified lines]# HF Inference ClientHF_TOKEN = os.getenv('HF_TOKEN')def get_inference_client(model_id):"""Return an InferenceClient with provider based on model_id."""provider = "groq" if model_id == "moonshotai/Kimi-K2-Instruct" else "auto"return InferenceClient(provider=provider,api_key=HF_TOKEN,bill_to="huggingface")# Type definitionsHistory = List[Tuple[str, str]]19 unmodified linestext_content = ""for item in user_content:if isinstance(item, dict) and item.get("type") == "text":text_content += item.get("text", "")user_content = text_content if text_content else str(user_content)messages.append({'role': 'user', 'content': user_content})10 unmodified linestext_content = ""for item in user_content:if isinstance(item, dict) and item.get("type") == "text":text_content += item.get("text", "")user_content = text_content if text_content else str(user_content)history.append([user_content, r['content']])8 unmodified linestext_content = ""for item in user_msg:if isinstance(item, dict) and item.get("type") == "text":text_content += item.get("text", "")user_msg = text_content if text_content else str(user_msg)messages.append({"role": "user", "content": user_msg})689 unmodified lineselse:messages.append({'role': 'user', 'content': enhanced_query})try:completion = client.chat.completions.create(model=_current_model["id"],messages=messages,stream=True,max_tokens=5000)content = ""for chunk in completion:if chunk.choices[0].delta.content:content += chunk.choices[0].delta.contentclean_code = remove_code_block(content)search_status = " (with web search)" if enable_search and tavily_client else ""if has_existing_html:# Fallback: If the model returns a full HTML file, use it directlyif clean_code.strip().startswith("<!DOCTYPE html>") or clean_code.strip().startswith("<html"):yield {code_output: gr.update(value=clean_code, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),sandbox: send_to_sandbox(clean_code) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",}else:last_html = _history[-1][1] if _history else ""modified_html = apply_search_replace_changes(last_html, clean_code)clean_html = remove_code_block(modified_html)yield {code_output: gr.update(value=clean_html, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),sandbox: send_to_sandbox(clean_html) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",}else:yield {code_output: gr.update(value=clean_code, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),sandbox: send_to_sandbox(clean_code) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",}# Handle response based on whether this is a modification or new generationif has_existing_html:# Fallback: If the model returns a full HTML file, use it directly122 unmodified linesoutputs=input)if not tavily_client:gr.Markdown("⚠️ Web search unavailable", visible=True)else:gr.Markdown("✅ Web search available", visible=True)model_display = gr.Markdown(f"**Model:** {AVAILABLE_MODELS[0]['name']}", visible=True) # Moonshot Kimi-K2def on_model_change(model_name):for m in AVAILABLE_MODELS:if m['name'] == model_name:
app.py+66-198