update
Browse files25 unmodified lines26272829303132333435363738394041424344454647484950515253239 unmodified lines293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667248 unmodified lines91691791891992092192225 unmodified lines)def parse_html_code(code: str) -> str:"""Extract HTML code from various formats"""code = code.strip()# If already clean HTML, return as-isif code.startswith('<!DOCTYPE') or code.startswith('<html'):return code# Try to extract from code blocksif '```html' in code:match = re.search(r'```html\s*(.*?)\s*```', code, re.DOTALL)if match:return match.group(1).strip()if '```' in code:match = re.search(r'```\s*(.*?)\s*```', code, re.DOTALL)if match:return match.group(1).strip()return codedef prettify_comfyui_json_for_html(json_content: str) -> str:"""Convert ComfyUI JSON to stylized HTML display with download button"""try:239 unmodified lines# and parse_multi_file_python_output are now imported from backend_parsers.pydef is_streamlit_code(code: str) -> bool:"""Check if code is Streamlit"""return 'import streamlit' in code or 'streamlit.run' in codedef is_gradio_code(code: str) -> bool:"""Check if code is Gradio"""return 'import gradio' in code or 'gr.' in codedef detect_sdk_from_code(code: str, language: str) -> str:"""Detect the appropriate SDK from code and language"""if language == "html":return "static"elif language == "transformers.js":return "static"elif language == "comfyui":return "static"elif language == "react":return "docker"elif language == "streamlit" or is_streamlit_code(code):return "docker"elif language == "gradio" or is_gradio_code(code):return "gradio"else:return "gradio" # Defaultdef add_anycoder_tag_to_readme(api, repo_id: str, app_port: Optional[int] = None) -> None:"""Download existing README, add anycoder tag and app_port if needed, and upload back.Preserves all existing README content and frontmatter.Args:api: HuggingFace API clientcss_patterns = [r'```css\s*\n([\s\S]*?)(?:```|\Z)',r'```\s*(?:style\.css|css)\s*\n([\s\S]*?)(?:```|\Z)']# Extract HTML contentfor pattern in html_patterns:html_match = re.search(pattern, code, re.IGNORECASE)if html_match:files['index.html'] = html_match.group(1).strip()break# Extract JavaScript contentfor pattern in js_patterns:js_match = re.search(pattern, code, re.IGNORECASE)if js_match:files['index.js'] = js_match.group(1).strip()break# Extract CSS contentfor pattern in css_patterns:css_match = re.search(pattern, code, re.IGNORECASE)if css_match:files['style.css'] = css_match.group(1).strip()break# Fallback: support === index.html === format if any file is missingif not (files['index.html'] and files['index.js'] and files['style.css']):# Use regex to extract sectionshtml_fallback = re.search(r'===\s*index\.html\s*===\s*\n([\s\S]+?)(?=\n===|$)', code, re.IGNORECASE)js_fallback = re.search(r'===\s*index\.js\s*===\s*\n([\s\S]+?)(?=\n===|$)', code, re.IGNORECASE)css_fallback = re.search(r'===\s*style\.css\s*===\s*\n([\s\S]+?)(?=\n===|$)', code, re.IGNORECASE)if html_fallback:files['index.html'] = html_fallback.group(1).strip()if js_fallback:files['index.js'] = js_fallback.group(1).strip()if css_fallback:files['style.css'] = css_fallback.group(1).strip()# Additional fallback: extract from numbered sections or file headersif not (files['index.html'] and files['index.js'] and files['style.css']):# Try patterns like "1. index.html:" or "**index.html**"patterns = [(r'(?:^\d+\.\s*|^##\s*|^\*\*\s*)index\.html(?:\s*:|\*\*:?)\s*\n([\s\S]+?)(?=\n(?:\d+\.|##|\*\*|===)|$)', 'index.html'),(r'(?:^\d+\.\s*|^##\s*|^\*\*\s*)index\.js(?:\s*:|\*\*:?)\s*\n([\s\S]+?)(?=\n(?:\d+\.|##|\*\*|===)|$)', 'index.js'),(r'(?:^\d+\.\s*|^##\s*|^\*\*\s*)style\.css(?:\s*:|\*\*:?)\s*\n([\s\S]+?)(?=\n(?:\d+\.|##|\*\*|===)|$)', 'style.css')]for pattern, file_key in patterns:if not files[file_key]:match = re.search(pattern, code, re.IGNORECASE | re.MULTILINE)if match:# Clean up the content by removing any code block markerscontent = match.group(1).strip()content = re.sub(r'^```\w*\s*\n', '', content)content = re.sub(r'\n```\s*$', '', content)files[file_key] = content.strip()return filesdef parse_python_requirements(code: str) -> Optional[str]:"""Extract requirements.txt content from code if present"""# Look for requirements.txt sectionreq_pattern = r'===\s*requirements\.txt\s*===\s*(.*?)(?====|$)'match = re.search(req_pattern, code, re.DOTALL | re.IGNORECASE)if match:requirements = match.group(1).strip()# Clean up code blocksrequirements = re.sub(r'^```\w*\s*', '', requirements, flags=re.MULTILINE)requirements = re.sub(r'```\s*$', '', requirements, flags=re.MULTILINE)return requirementsreturn Nonedef strip_tool_call_markers(text):"""Remove TOOL_CALL markers and thinking tags that some LLMs add to their output."""if not text:return text# Remove [TOOL_CALL] and [/TOOL_CALL] markerstext = re.sub(r'\[/?TOOL_CALL\]', '', text, flags=re.IGNORECASE)# Remove <think> and </think> tags and their contenttext = re.sub(r'<think>[\s\S]*?</think>', '', text, flags=re.IGNORECASE)# Remove any remaining unclosed <think> tags at the starttext = re.sub(r'^<think>[\s\S]*?(?=\n|$)', '', text, flags=re.IGNORECASE | re.MULTILINE)# Remove any remaining </think> tagstext = re.sub(r'</think>', '', text, flags=re.IGNORECASE)# Remove standalone }} that appears with tool calls# Only remove if it's on its own line or at the endtext = re.sub(r'^\s*\}\}\s*$', '', text, flags=re.MULTILINE)return text.strip()def remove_code_block(text):"""Remove code block markers from text."""# First strip any tool call markerstext = strip_tool_call_markers(text)# Try to match code blocks with language markerspatterns = [r'```(?:html|HTML)\n([\s\S]+?)\n```', # Match ```html or ```HTMLr'```\n([\s\S]+?)\n```', # Match code blocks without language markersr'```([\s\S]+?)```' # Match code blocks without line breaks]for pattern in patterns:match = re.search(pattern, text, re.DOTALL)if match:extracted = match.group(1).strip()# Remove a leading language marker line (e.g., 'python') if presentif extracted.split('\n', 1)[0].strip().lower() in ['python', 'html', 'css', 'javascript', 'json', 'c', 'cpp', 'markdown', 'latex', 'jinja2', 'typescript', 'yaml', 'dockerfile', 'shell', 'r', 'sql']:return extracted.split('\n', 1)[1] if '\n' in extracted else ''return extracted# If no code block is found, return as-isreturn text.strip()def extract_import_statements(code):"""Extract import statements from generated code."""import_statements = []# Built-in Python modules to excludebuiltin_modules = {'os', 'sys', 'json', 'time', 'datetime', 'random', 'math', 're', 'collections','itertools', 'functools', 'pathlib', 'urllib', 'http', 'email', 'html', 'xml','csv', 'tempfile', 'shutil', 'subprocess', 'threading', 'multiprocessing','asyncio', 'logging', 'typing', 'base64', 'hashlib', 'secrets', 'uuid','copy', 'pickle', 'io', 'contextlib', 'warnings', 'sqlite3', 'gzip', 'zipfile','tarfile', 'socket', 'ssl', 'platform', 'getpass', 'pwd', 'grp', 'stat','glob', 'fnmatch', 'linecache', 'traceback', 'inspect', 'keyword', 'token','tokenize', 'ast', 'code', 'codeop', 'dis', 'py_compile', 'compileall','importlib', 'pkgutil', 'modulefinder', 'runpy', 'site', 'sysconfig'}try:# Try to parse as Python ASTtree = ast.parse(code)for node in ast.walk(tree):if isinstance(node, ast.Import):for alias in node.names:module_name = alias.name.split('.')[0]if module_name not in builtin_modules and not module_name.startswith('_'):import_statements.append(f"import {alias.name}")elif isinstance(node, ast.ImportFrom):if node.module:module_name = node.module.split('.')[0]if module_name not in builtin_modules and not module_name.startswith('_'):names = [alias.name for alias in node.names]import_statements.append(f"from {node.module} import {', '.join(names)}")except SyntaxError:# Fallback: use regex to find import statementsfor line in code.split('\n'):line = line.strip()if line.startswith('import ') or line.startswith('from '):# Check if it's not a builtin moduleif line.startswith('import '):module_name = line.split()[1].split('.')[0]elif line.startswith('from '):module_name = line.split()[1].split('.')[0]if module_name not in builtin_modules and not module_name.startswith('_'):import_statements.append(line)return list(set(import_statements)) # Remove duplicatesdef generate_requirements_txt_with_llm(import_statements):"""Generate requirements.txt content using LLM based on import statements."""if not import_statements:return "# No additional dependencies required\n"# Use a lightweight model for this tasktry:client = get_inference_client("zai-org/GLM-4.6", "auto")actual_model_id = get_real_model_id("zai-org/GLM-4.6")imports_text = '\n'.join(import_statements)prompt = f"""Based on the following Python import statements, generate a comprehensive requirements.txt file with all necessary and commonly used related packages:{imports_text}Instructions:- Include the direct packages needed for the imports- Include commonly used companion packages and dependencies for better functionality- Use correct PyPI package names (e.g., PIL -> Pillow, sklearn -> scikit-learn)- IMPORTANT: For diffusers, ALWAYS use: git+https://github.com/huggingface/diffusers- IMPORTANT: For transformers, ALWAYS use: git+https://github.com/huggingface/transformers- IMPORTANT: If diffusers is installed, also include transformers and sentencepiece as they usually go together- Examples of comprehensive dependencies:* diffusers often needs: git+https://github.com/huggingface/transformers, sentencepiece, accelerate, torch, tokenizers* transformers often needs: accelerate, torch, tokenizers, datasets* gradio often needs: requests, Pillow for image handling* pandas often needs: numpy, openpyxl for Excel files* matplotlib often needs: numpy, pillow for image saving* sklearn often needs: numpy, scipy, joblib* streamlit often needs: pandas, numpy, requests* opencv-python often needs: numpy, pillow* fastapi often needs: uvicorn, pydantic* torch often needs: torchvision, torchaudio (if doing computer vision/audio)- Include packages for common file formats if relevant (openpyxl, python-docx, PyPDF2)- Do not include Python built-in modules- Do not specify versions unless there are known compatibility issues- One package per line- If no external packages are needed, return "# No additional dependencies required"🚨 CRITICAL OUTPUT FORMAT:- Output ONLY the package names, one per line (plain text format)- Do NOT use markdown formatting (no ```, no bold, no headings, no lists)- Do NOT add any explanatory text before or after the package list- Do NOT wrap the output in code blocks- Just output raw package names as they would appear in requirements.txtGenerate a comprehensive requirements.txt that ensures the application will work smoothly:"""messages = [{"role": "system", "content": "You are a Python packaging expert specializing in creating comprehensive, production-ready requirements.txt files. Output ONLY plain text package names without any markdown formatting, code blocks, or explanatory text. Your goal is to ensure applications work smoothly by including not just direct dependencies but also commonly needed companion packages, popular extensions, and supporting libraries that developers typically need together."},{"role": "user", "content": prompt}]response = client.chat.completions.create(model=actual_model_id,messages=messages,max_tokens=1024,temperature=0.1)requirements_content = response.choices[0].message.content.strip()# Clean up the response in case it includes extra formattingif '```' in requirements_content:requirements_content = remove_code_block(requirements_content)# Enhanced cleanup for markdown and formattinglines = requirements_content.split('\n')clean_lines = []for line in lines:stripped_line = line.strip()# Skip lines that are markdown formattingif (stripped_line == '```' orstripped_line.startswith('```') orstripped_line.startswith('#') and not stripped_line.startswith('# ') or # Skip markdown headers but keep commentsstripped_line.startswith('**') or # Skip bold textstripped_line.startswith('*') and not stripped_line[1:2].isalnum() or # Skip markdown lists but keep package names starting with *stripped_line.startswith('-') and not stripped_line[1:2].isalnum() or # Skip markdown lists but keep package names starting with -stripped_line.startswith('===') or # Skip section dividersstripped_line.startswith('---') or # Skip horizontal rulesstripped_line.lower().startswith('here') or # Skip explanatory textstripped_line.lower().startswith('this') or # Skip explanatory textstripped_line.lower().startswith('the') or # Skip explanatory textstripped_line.lower().startswith('based on') or # Skip explanatory textstripped_line == ''): # Skip empty lines unless they're at natural boundariescontinue# Keep lines that look like valid package specifications# Valid lines: package names, git+https://, comments starting with "# "if (stripped_line.startswith('# ') or # Valid commentsstripped_line.startswith('git+') or # Git dependenciesstripped_line[0].isalnum() or # Package names start with alphanumeric'==' in stripped_line or # Version specifications'>=' in stripped_line or # Version specifications'<=' in stripped_line): # Version specificationsclean_lines.append(line)requirements_content = '\n'.join(clean_lines).strip()# Ensure it ends with a newlineif requirements_content and not requirements_content.endswith('\n'):requirements_content += '\n'return requirements_content if requirements_content else "# No additional dependencies required\n"except Exception as e:# Fallback: simple extraction with basic mappingprint(f"[Deploy] Warning: LLM requirements generation failed: {e}, using fallback")dependencies = set()special_cases = {'PIL': 'Pillow','sklearn': 'scikit-learn','skimage': 'scikit-image','bs4': 'beautifulsoup4'}for stmt in import_statements:if stmt.startswith('import '):module_name = stmt.split()[1].split('.')[0]package_name = special_cases.get(module_name, module_name)dependencies.add(package_name)elif stmt.startswith('from '):module_name = stmt.split()[1].split('.')[0]package_name = special_cases.get(module_name, module_name)dependencies.add(package_name)if dependencies:return '\n'.join(sorted(dependencies)) + '\n'else:return "# No additional dependencies required\n"def parse_multi_file_python_output(code: str) -> Dict[str, str]:"""Parse multi-file Python output (e.g., Gradio, Streamlit)"""files = {}# Pattern to match file sectionspattern = r'===\s*(\S+\.(?:py|txt))\s*===\s*(.*?)(?====|$)'matches = re.finditer(pattern, code, re.DOTALL | re.IGNORECASE)for match in matches:filename = match.group(1).strip()content = match.group(2).strip()# Clean up code blocks if presentcontent = re.sub(r'^```\w*\s*', '', content, flags=re.MULTILINE)content = re.sub(r'```\s*$', '', content, flags=re.MULTILINE)files[filename] = content# If no files were parsed, treat as single app.pyif not files:# Clean up code blocksclean_code = re.sub(r'^```\w*\s*', '', code, flags=re.MULTILINE)clean_code = re.sub(r'```\s*$', '', clean_code, flags=re.MULTILINE)files['app.py'] = clean_code.strip()return filesdef is_streamlit_code(code: str) -> bool:"""Check if code is Streamlit"""return 'import streamlit' in code or 'streamlit.run' in code248 unmodified linesprint(f"[Deploy] {error_msg}")return False, error_msg, None# Write transformers.js files to temp directoryfor filename, content in files.items():file_path = temp_path / filenameprint(f"[Deploy] Writing {filename} ({len(content)} chars) to {file_path}")25 unmodified lines262728293031239 unmodified lines271272273274275276248 unmodified lines52552652752852953053125 unmodified lines)def prettify_comfyui_json_for_html(json_content: str) -> str:"""Convert ComfyUI JSON to stylized HTML display with download button"""try:239 unmodified lines# and parse_multi_file_python_output are now imported from backend_parsers.pydef is_streamlit_code(code: str) -> bool:"""Check if code is Streamlit"""return 'import streamlit' in code or 'streamlit.run' in code248 unmodified linesprint(f"[Deploy] {error_msg}")return False, error_msg, None# Write transformers.js files to temp directoryfor filename, content in files.items():file_path = temp_path / filenameprint(f"[Deploy] Writing {filename} ({len(content)} chars) to {file_path}")
backend_deploy.py+1-392