update
Browse files472 unmodified lines473474475476477478479480297 unmodified lines778779780781782783784671 unmodified lines1456145714581459146014611462263 unmodified lines17261727172817291730173117321733173417351736173717381739174017411742174317441745174617474100 unmodified lines5848584958505851585258535854669 unmodified lines65246525652665276528652965301 unmodified line6532653365346535653665376538653965406541654265436544654565462890 unmodified lines9437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470472 unmodified lines[dependencies]```**Single vs Multi-File Decision:**- Use single file for simple applications (< 100 lines)- Use multi-file structure for complex applications with:- Multiple models or processing pipelines- Extensive utility functions297 unmodified lines```**Single vs Multi-File Decision:**- Use single file for simple applications (< 100 lines)- Use multi-file structure for complex applications with:- Multiple models or processing pipelines- Extensive utility functions671 unmodified lines```**Single vs Multi-File Decision:**- Use single file for simple applications (< 100 lines)- Use multi-file structure for complex applications with:- Multiple pages or sections- Extensive data processing263 unmodified linesGradioFollowUpSystemPrompt = """You are an expert Gradio developer modifying an existing Gradio application.The user wants to apply changes based on their request.CRITICAL: You MUST maintain the original multi-file structure when making modifications.Do NOT use SEARCH/REPLACE blocks. Instead, output the complete modified files using the same format as the original generation.**Output Format for Modified Gradio Apps:**When modifying multi-file Gradio applications, use this exact format:```=== app.py ===[complete modified app.py content]=== utils.py ===[complete modified utils.py content - only if it exists and needs changes]=== requirements.txt ===[complete modified requirements.txt content]```**File Modification Guidelines:**- Only output files that actually need changes4100 unmodified lines'=== index.html ===' in last_assistant_msg or'=== index.js ===' in last_assistant_msg or'=== style.css ===' in last_assistant_msg or'=== src/App.svelte ===' in last_assistant_msg):has_existing_content = True# If this is a modification request, try to apply search/replace first669 unmodified lineselif language == "gradio":# Handle Gradio output - check if it's multi-file format or single fileif ('=== app.py ===' in content or '=== requirements.txt ===' in content):# Model returned complete multi-file Gradio output (new generation or followup with multi-file format)_history.append([query, content])yield {code_output: content,1 unmodified linehistory_output: history_to_chatbot_messages(_history),}elif has_existing_content:# Model returned search/replace changes for Gradio - apply themlast_content = _history[-1][1] if _history and len(_history[-1]) > 1 else ""modified_content = apply_search_replace_changes(last_content, content)_history.append([query, modified_content])yield {code_output: modified_content,history: _history,history_output: history_to_chatbot_messages(_history),}else:# Fallback - treat as single file Gradio app_history.append([query, content])2890 unmodified lines# File doesn't exist or can't be accessed, so we should uploadshould_upload_requirements = True# Upload requirements.txt only if neededif should_upload_requirements:try:with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as f:f.write(requirements_content)requirements_temp_path = f.nameapi.upload_file(path_or_fileobj=requirements_temp_path,path_in_repo="requirements.txt",repo_id=repo_id,repo_type="space")except Exception as e:error_msg = str(e)if "403 Forbidden" in error_msg and "write token" in error_msg:return gr.update(value=f"Error uploading requirements.txt: Permission denied. Please ensure you have write access to {repo_id} and your token has the correct permissions.", visible=True)else:return gr.update(value=f"Error uploading requirements.txt: {e}", visible=True)finally:import osif 'requirements_temp_path' in locals():os.unlink(requirements_temp_path)# Add anycoder tag to existing READMEadd_anycoder_tag_to_readme(api, repo_id)# Now upload the main app.py filefile_name = "app.py"with tempfile.NamedTemporaryFile("w", suffix=f".{file_name.split('.')[-1]}", delete=False) as f:f.write(code)472 unmodified lines473474475476477478479480481482483484485486487488489490297 unmodified lines788789790791792793794671 unmodified lines1466146714681469147014711472263 unmodified lines17361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517664100 unmodified lines586758685869587058715872587358745875669 unmodified lines6545654665476548654965506551655265536554655565566557655865596560656165621 unmodified line65646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366242890 unmodified lines951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592472 unmodified lines[dependencies]```**🚨 CRITICAL: Always Generate requirements.txt for New Applications**- ALWAYS include requirements.txt when creating new Gradio applications- Generate comprehensive, production-ready dependencies based on your code- Include not just direct imports but also commonly needed companion packages- Use correct PyPI package names (e.g., PIL → Pillow, sklearn → scikit-learn)- For diffusers: use `git+https://github.com/huggingface/diffusers`- For transformers: use `git+https://github.com/huggingface/transformers`- Include supporting packages (accelerate, torch, tokenizers, etc.) when using ML libraries- Your requirements.txt should ensure the application works smoothly in production**Single vs Multi-File Decision:**- Use single file for simple applications (< 100 lines) - but still generate requirements.txt if dependencies exist- Use multi-file structure for complex applications with:- Multiple models or processing pipelines- Extensive utility functions297 unmodified lines```**Single vs Multi-File Decision:**- Use single file for simple applications (< 100 lines) - but still generate requirements.txt if dependencies exist- Use multi-file structure for complex applications with:- Multiple models or processing pipelines- Extensive utility functions671 unmodified lines```**Single vs Multi-File Decision:**- Use single file for simple applications (< 100 lines) - but still generate requirements.txt if dependencies exist- Use multi-file structure for complex applications with:- Multiple pages or sections- Extensive data processing263 unmodified linesGradioFollowUpSystemPrompt = """You are an expert Gradio developer modifying an existing Gradio application.The user wants to apply changes based on their request.🚨 CRITICAL INSTRUCTION: You MUST maintain the original multi-file structure when making modifications.❌ Do NOT use SEARCH/REPLACE blocks.❌ Do NOT output everything in one combined block.✅ Instead, output the complete modified files using the EXACT same multi-file format as the original generation.**MANDATORY Output Format for Modified Gradio Apps:**You MUST use this exact format with file separators. DO NOT deviate from this format:=== app.py ===[complete modified app.py content]**CRITICAL FORMATTING RULES:**- ALWAYS start each file with exactly "=== filename ===" (three equals signs before and after)- NEVER combine files into one block- NEVER use SEARCH/REPLACE blocks like <<<<<<< SEARCH- ALWAYS include app.py if it needs changes- Only include other files (utils.py, models.py, etc.) if they exist and need changes- Each file section must be complete and standalone- The format MUST match the original multi-file structure exactly**🚨 CRITICAL: DO NOT GENERATE requirements.txt**- requirements.txt is automatically generated from your app.py imports- Do NOT include requirements.txt in your output unless the user specifically asks to modify dependencies- The system will automatically extract imports from app.py and generate requirements.txt- This prevents unnecessary changes to dependencies**File Modification Guidelines:**- Only output files that actually need changes4100 unmodified lines'=== index.html ===' in last_assistant_msg or'=== index.js ===' in last_assistant_msg or'=== style.css ===' in last_assistant_msg or'=== src/App.svelte ===' in last_assistant_msg or'=== app.py ===' in last_assistant_msg or'=== requirements.txt ===' in last_assistant_msg):has_existing_content = True# If this is a modification request, try to apply search/replace first669 unmodified lineselif language == "gradio":# Handle Gradio output - check if it's multi-file format or single fileif ('=== app.py ===' in content or '=== requirements.txt ===' in content):# Model returned multi-file Gradio output - ensure requirements.txt is presentfiles = parse_multi_file_python_output(content)if files and 'app.py' in files:# Check if requirements.txt is missing and auto-generate itif 'requirements.txt' not in files:import_statements = extract_import_statements(files['app.py'])requirements_content = generate_requirements_txt_with_llm(import_statements)files['requirements.txt'] = requirements_content# Reformat with the auto-generated requirements.txtcontent = format_multi_file_python_output(files)_history.append([query, content])yield {code_output: content,1 unmodified linehistory_output: history_to_chatbot_messages(_history),}elif has_existing_content:# Check if this is a followup that should maintain multi-file structurelast_content = _history[-1][1] if _history and len(_history[-1]) > 1 else ""# If the original was multi-file but the response isn't, try to convert itif ('=== app.py ===' in last_content or '=== requirements.txt ===' in last_content):# Original was multi-file, but response is single block - need to convertif not ('=== app.py ===' in content or '=== requirements.txt ===' in content):# Try to parse as single-block Gradio code and convert to multi-file formatclean_content = remove_code_block(content)if 'import gradio' in clean_content or 'from gradio' in clean_content:# This looks like Gradio code, convert to multi-file formatfiles = parse_multi_file_python_output(clean_content)if not files:# Single file - create multi-file structurefiles = {'app.py': clean_content}# Extract requirements from importsimport_statements = extract_import_statements(clean_content)requirements_content = generate_requirements_txt_with_llm(import_statements)files['requirements.txt'] = requirements_content# Format as multi-file outputformatted_content = format_multi_file_python_output(files)_history.append([query, formatted_content])yield {code_output: formatted_content,history: _history,history_output: history_to_chatbot_messages(_history),}else:# Not Gradio code, apply search/replacemodified_content = apply_search_replace_changes(last_content, content)_history.append([query, modified_content])yield {code_output: modified_content,history: _history,history_output: history_to_chatbot_messages(_history),}else:# Response is already multi-file format_history.append([query, content])yield {code_output: content,history: _history,history_output: history_to_chatbot_messages(_history),}else:# Original was single file, apply search/replacemodified_content = apply_search_replace_changes(last_content, content)_history.append([query, modified_content])yield {code_output: modified_content,history: _history,history_output: history_to_chatbot_messages(_history),}else:# Fallback - treat as single file Gradio app_history.append([query, content])2890 unmodified lines# File doesn't exist or can't be accessed, so we should uploadshould_upload_requirements = True# Note: requirements.txt upload is now handled by the multi-file commit logic below# This ensures all files are committed atomically in a single operation# Add anycoder tag to existing READMEadd_anycoder_tag_to_readme(api, repo_id)# Check if code contains multi-file formatif ('=== app.py ===' in code or '=== requirements.txt ===' in code):# Parse multi-file format and upload each file separatelyfiles = parse_multi_file_python_output(code)if files:# Ensure requirements.txt is present - auto-generate if missingif 'app.py' in files and 'requirements.txt' not in files:import_statements = extract_import_statements(files['app.py'])requirements_content = generate_requirements_txt_with_llm(import_statements)files['requirements.txt'] = requirements_contenttry:from huggingface_hub import CommitOperationAddoperations = []temp_files = []# Create CommitOperation for each filefor filename, content in files.items():# Create temporary filewith tempfile.NamedTemporaryFile("w", suffix=f".{filename.split('.')[-1]}", delete=False) as f:f.write(content)temp_path = f.nametemp_files.append(temp_path)# Add to operationsoperations.append(CommitOperationAdd(path_in_repo=filename,path_or_fileobj=temp_path))# Commit all files at onceapi.create_commit(repo_id=repo_id,operations=operations,commit_message=f"{'Update' if is_update else 'Deploy'} Gradio app with multiple files",repo_type="space")# Clean up temp filesfor temp_path in temp_files:try:os.unlink(temp_path)except Exception:passspace_url = f"https://huggingface.co/spaces/{repo_id}"action_text = "Updated" if is_update else "Deployed"return gr.update(value=f"✅ {action_text}! [Open your Space here]({space_url})", visible=True)except Exception as e:# Clean up temp files on errorfor temp_path in temp_files:try:os.unlink(temp_path)except Exception:passerror_msg = str(e)if "403 Forbidden" in error_msg and "write token" in error_msg:return gr.update(value=f"Error: Permission denied. Please ensure you have write access to {repo_id} and your token has the correct permissions.", visible=True)else:return gr.update(value=f"Error uploading multi-file app: {e}", visible=True)else:# Fallback to single file if parsing failedpass# Single file upload (fallback or non-multi-file format)file_name = "app.py"with tempfile.NamedTemporaryFile("w", suffix=f".{file_name.split('.')[-1]}", delete=False) as f:f.write(code)
app.py+170-48