update streamlit issue
Browse filesFiles changed (2)
- anycoder_app/prompts.py+82-31
- anycoder_app/ui.py+97-72
97 unmodified lines98991001011021031041051061071081091101111122 unmodified lines11511611711811912012112212312412512612712812913013113213 unmodified lines1461471481491501511521531541551561571581591601611621631641651662 unmodified lines16917017117217317417517617717817918018118297 unmodified lines## Multi-File Application StructureWhen creating complex Streamlit applications, organize your code into multiple files for better maintainability:**File Organization:**- `app.py` or `streamlit_app.py` - Main application entry point- `utils.py` - Utility functions and helpers- `models.py` - Model loading and inference functions- `config.py` - Configuration and constants- `requirements.txt` - Python dependencies- `pages/` - Additional pages for multi-page apps- Additional modules as needed (e.g., `data_processing.py`, `components.py`)**🚨 CRITICAL: DO NOT Generate README.md Files**2 unmodified lines- Generating a README.md will break the deployment process- Only generate the code files listed above**Output Format for Multi-File Apps:**When generating multi-file applications, use this exact format:```=== streamlit_app.py ===[main application code]=== utils.py ===[utility functions]=== requirements.txt ===[dependencies]```**🚨 CRITICAL: requirements.txt Formatting Rules**13 unmodified lines- pandas```**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 processing- Complex UI components- Multiple models or APIs- When user specifically requests modular structure**Multi-Page Apps:**For multi-page Streamlit apps, use the pages/ directory structure:```=== streamlit_app.py ===[main page]=== pages/1_📊_Analytics.py ===[analytics page]2 unmodified lines```Requirements:1. Create a modern, responsive Streamlit application2. Use appropriate Streamlit components and layouts3. Include proper error handling and loading states4. Follow Streamlit best practices for performance5. Use caching (@st.cache_data, @st.cache_resource) appropriately6. Include proper session state management when needed7. Make the UI intuitive and user-friendly8. Add helpful tooltips and documentationIMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder"""97 unmodified lines98991001011021031041051061071081091101111121132 unmodified lines11611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418513 unmodified lines1992002012022032042052062072082092102112122132142152162 unmodified lines21922022122222322422522622722822923023123223397 unmodified lines## Multi-File Application StructureWhen creating Streamlit applications, you MUST organize your code into multiple files for proper deployment:**File Organization (CRITICAL - Always Include These):**- `Dockerfile` - Docker configuration for deployment (REQUIRED)- `streamlit_app.py` - Main application entry point (REQUIRED)- `requirements.txt` - Python dependencies (REQUIRED)- `utils.py` - Utility functions and helpers (optional)- `models.py` - Model loading and inference functions (optional)- `config.py` - Configuration and constants (optional)- `pages/` - Additional pages for multi-page apps (optional)- Additional modules as needed (e.g., `data_processing.py`, `components.py`)**🚨 CRITICAL: DO NOT Generate README.md Files**2 unmodified lines- Generating a README.md will break the deployment process- Only generate the code files listed above**Output Format for Streamlit Apps:**You MUST use this exact format and ALWAYS include Dockerfile, streamlit_app.py, and requirements.txt:```=== Dockerfile ===[Dockerfile content]=== streamlit_app.py ===[main application code]=== requirements.txt ===[dependencies]=== utils.py ===[utility functions - optional]```**🚨 CRITICAL: Dockerfile Requirements (MANDATORY for HuggingFace Spaces)**Your Dockerfile MUST follow these exact specifications:- Use Python 3.11+ base image (e.g., FROM python:3.11-slim)- Set up a user with ID 1000 for proper permissions:```RUN useradd -m -u 1000 userUSER userENV HOME=/home/user \\PATH=/home/user/.local/bin:$PATHWORKDIR $HOME/app```- ALWAYS use --chown=user with COPY and ADD commands:```COPY --chown=user requirements.txt .COPY --chown=user . .```- Install dependencies: RUN pip install --no-cache-dir -r requirements.txt- Expose port 7860 (HuggingFace Spaces default): EXPOSE 7860- Start with: CMD ["streamlit", "run", "streamlit_app.py", "--server.port=7860", "--server.address=0.0.0.0"]**Example Dockerfile structure (USE THIS AS TEMPLATE):**```dockerfileFROM python:3.11-slim# Set up user with ID 1000RUN useradd -m -u 1000 userUSER userENV HOME=/home/user \\PATH=/home/user/.local/bin:$PATH# Set working directoryWORKDIR $HOME/app# Copy requirements file with proper ownershipCOPY --chown=user requirements.txt .# Install dependenciesRUN pip install --no-cache-dir -r requirements.txt# Copy application files with proper ownershipCOPY --chown=user . .# Expose port 7860EXPOSE 7860# Start Streamlit appCMD ["streamlit", "run", "streamlit_app.py", "--server.port=7860", "--server.address=0.0.0.0"]```**🚨 CRITICAL: requirements.txt Formatting Rules**13 unmodified lines- pandas```**Multi-Page Apps:**For multi-page Streamlit apps, use the pages/ directory structure:```=== Dockerfile ===[Dockerfile content]=== streamlit_app.py ===[main page]=== requirements.txt ===[dependencies]=== pages/1_📊_Analytics.py ===[analytics page]2 unmodified lines```Requirements:1. ALWAYS include Dockerfile, streamlit_app.py, and requirements.txt in your output2. Create a modern, responsive Streamlit application3. Use appropriate Streamlit components and layouts4. Include proper error handling and loading states5. Follow Streamlit best practices for performance6. Use caching (@st.cache_data, @st.cache_resource) appropriately7. Include proper session state management when needed8. Make the UI intuitive and user-friendly9. Add helpful tooltips and documentationIMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder"""
1160 unmodified lines11611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451160 unmodified linesaction_text = "Updated" if is_update else "Deployed"return gr.update(value=f"✅ {action_text}! [Open your React Space here]({space_url})", visible=True)# Streamlit logic# Generate requirements.txt for Streamlit apps and upload only if neededimport_statements = extract_import_statements(code)requirements_content = generate_requirements_txt_with_llm(import_statements)import tempfile# Check if we need to upload requirements.txtshould_upload_requirements = Trueif is_update:try:# Try to get existing requirements.txt contentexisting_requirements = api.hf_hub_download(repo_id=repo_id,filename="requirements.txt",repo_type="space")with open(existing_requirements, 'r') as f:existing_content = f.read().strip()# Compare with new contentif existing_content == requirements_content.strip():should_upload_requirements = Falseexcept Exception:# 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)# Upload the user's code to src/streamlit_app.py (for both new and existing spaces)with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as f:f.write(code)temp_path = f.nametry:api.upload_file(path_or_fileobj=temp_path,path_in_repo="src/streamlit_app.py",repo_id=repo_id,repo_type="space")space_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:error_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 Streamlit app: {e}", visible=True)finally:import osos.unlink(temp_path)except Exception as e:error_prefix = "Error duplicating Streamlit space" if not is_update else "Error updating Streamlit space"1160 unmodified lines116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701160 unmodified linesaction_text = "Updated" if is_update else "Deployed"return gr.update(value=f"✅ {action_text}! [Open your React Space here]({space_url})", visible=True)# Streamlit logic - Parse multi-file structurefiles = parse_multi_file_python_output(code)if not files:return gr.update(value="Error: Could not parse Streamlit output. Please regenerate the code.", visible=True)# Verify required files existhas_streamlit_app = 'streamlit_app.py' in files or 'app.py' in fileshas_requirements = 'requirements.txt' in fileshas_dockerfile = 'Dockerfile' in filesif not has_streamlit_app:return gr.update(value="Error: Missing streamlit_app.py. Please regenerate the code.", visible=True)# If Dockerfile or requirements.txt is missing, generate themif not has_dockerfile:# Generate default Dockerfilefiles['Dockerfile'] = """FROM python:3.11-slim# Set up user with ID 1000RUN useradd -m -u 1000 userUSER userENV HOME=/home/user \\PATH=/home/user/.local/bin:$PATH# Set working directoryWORKDIR $HOME/app# Copy requirements file with proper ownershipCOPY --chown=user requirements.txt .# Install dependenciesRUN pip install --no-cache-dir -r requirements.txt# Copy application files with proper ownershipCOPY --chown=user . .# Expose port 7860EXPOSE 7860# Start Streamlit appCMD ["streamlit", "run", "streamlit_app.py", "--server.port=7860", "--server.address=0.0.0.0"]"""if not has_requirements:# Generate requirements.txt from imports in the main app filemain_app = files.get('streamlit_app.py') or files.get('app.py', '')import_statements = extract_import_statements(main_app)files['requirements.txt'] = generate_requirements_txt_with_llm(import_statements)# Upload Streamlit filesimport tempfileimport timefor file_name, file_content in files.items():if not file_content:continuesuccess = Falselast_error = Nonemax_attempts = 3for attempt in range(max_attempts):try:# Determine file extensionif file_name == 'Dockerfile':suffix = ''else:suffix = f".{file_name.split('.')[-1]}"with tempfile.NamedTemporaryFile("w", suffix=suffix, delete=False) as f:f.write(file_content)temp_path = f.nameapi.upload_file(path_or_fileobj=temp_path,path_in_repo=file_name,repo_id=repo_id,repo_type="space")success = Truebreakexcept Exception as e:last_error = eerror_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)if attempt < max_attempts - 1:time.sleep(2)finally:import osif 'temp_path' in locals():os.unlink(temp_path)if not success:return gr.update(value=f"Error uploading {file_name}: {last_error}", visible=True)# Add anycoder tag and app_port to existing READMEadd_anycoder_tag_to_readme(api, repo_id, app_port=7860)space_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 Streamlit Space here]({space_url})", visible=True)except Exception as e:error_prefix = "Error duplicating Streamlit space" if not is_update else "Error updating Streamlit space"
anycoder_app/prompts.py+82-31
anycoder_app/ui.py+97-72