clean up code
Browse filesFiles changed (2)
11 unmodified lines121314151617355 unmodified lines373374375376377378103 unmodified lines48248348448548648711 unmodified linesimport secretsimport base64import urllib.parse# Import only what we need, avoiding Gradio UI importsimport sys355 unmodified lines)@app.post("/api/generate")async def generate_code(request: CodeGenerationRequest,103 unmodified lines})yield f"data: {event_data}\n\n"# Send completion event (optimized - no timestamp in hot path)completion_data = json.dumps({"type": "complete",11 unmodified lines12131415161718355 unmodified lines374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510103 unmodified lines61461561661761861962062162211 unmodified linesimport secretsimport base64import urllib.parseimport re# Import only what we need, avoiding Gradio UI importsimport sys355 unmodified lines)def cleanup_generated_code(code: str, language: str) -> str:"""Remove LLM explanatory text and extract only the actual code"""try:original_code = code# Special handling for ComfyUI JSONif language == "comfyui":# Try to parse as JSON firsttry:json.loads(code)return code # If it parses, return as-isexcept json.JSONDecodeError:pass# Find the last } in the codelast_brace = code.rfind('}')if last_brace != -1:# Extract everything up to and including the last }potential_json = code[:last_brace + 1]# Try to find where the JSON actually startsjson_start = 0if '```json' in potential_json:match = re.search(r'```json\s*\n', potential_json)if match:json_start = match.end()elif '```' in potential_json:match = re.search(r'```\s*\n', potential_json)if match:json_start = match.end()# Extract the JSONcleaned_json = potential_json[json_start:].strip()cleaned_json = re.sub(r'```\s*$', '', cleaned_json).strip()# Validatetry:json.loads(cleaned_json)return cleaned_jsonexcept json.JSONDecodeError:pass# General cleanup for code languages# Remove markdown code blocks and extract codeif '```' in code:# Pattern to match code blocks with language specifierspatterns = [r'```(?:html|HTML)\s*\n([\s\S]+?)(?:\n```|$)',r'```(?:python|py|Python)\s*\n([\s\S]+?)(?:\n```|$)',r'```(?:javascript|js|jsx|JavaScript)\s*\n([\s\S]+?)(?:\n```|$)',r'```(?:typescript|ts|tsx|TypeScript)\s*\n([\s\S]+?)(?:\n```|$)',r'```\s*\n([\s\S]+?)(?:\n```|$)', # Generic code block]for pattern in patterns:match = re.search(pattern, code, re.IGNORECASE)if match:code = match.group(1).strip()break# Remove common LLM explanatory patterns# Remove lines that start with explanatory textlines = code.split('\n')cleaned_lines = []in_code = Falsefor line in lines:stripped = line.strip()# Skip common explanatory patterns at the startif not in_code and (stripped.lower().startswith('here') orstripped.lower().startswith('this') orstripped.lower().startswith('the above') orstripped.lower().startswith('note:') orstripped.lower().startswith('explanation:') orstripped.lower().startswith('to use') orstripped.lower().startswith('usage:') orstripped.lower().startswith('instructions:') orstripped.startswith('===') and '===' in stripped # Section markers):continue# Once we hit actual code, we're inif stripped and not stripped.startswith('#') and not stripped.startswith('//'):in_code = Truecleaned_lines.append(line)code = '\n'.join(cleaned_lines).strip()# Remove trailing explanatory text after the code ends# For HTML: remove everything after final closing tagif language == "html":# Find last </html> or </body> or </div> at root levellast_html = code.rfind('</html>')last_body = code.rfind('</body>')last_tag = max(last_html, last_body)if last_tag != -1:# Check if there's significant text afterafter_tag = code[last_tag + 7:].strip() # +7 for </html> lengthif after_tag and len(after_tag) > 100: # Significant explanatory textcode = code[:last_tag + 7].strip()# For Python: remove text after the last function/class definition or code blockelif language in ["gradio", "streamlit"]:# Find the last line that looks like actual code (not comments or blank)lines = code.split('\n')last_code_line = -1for i in range(len(lines) - 1, -1, -1):stripped = lines[i].strip()if stripped and not stripped.startswith('#') and not stripped.startswith('"""') and not stripped.startswith("'''"):# This looks like actual codelast_code_line = ibreakif last_code_line != -1 and last_code_line < len(lines) - 5:# If there are more than 5 lines after last code, likely explanatorycode = '\n'.join(lines[:last_code_line + 1])# Return cleaned code or original if cleaning made it too shortif len(code) > 50:return codeelse:return original_codeexcept Exception as e:print(f"[Code Cleanup] Error for {language}: {e}")return code@app.post("/api/generate")async def generate_code(request: CodeGenerationRequest,103 unmodified lines})yield f"data: {event_data}\n\n"# Clean up generated code (remove LLM explanatory text and markdown)generated_code = cleanup_generated_code(generated_code, language)# Send completion event (optimized - no timestamp in hot path)completion_data = json.dumps({"type": "complete",
273 unmodified lines274275276277278279280273 unmodified linesBuild with AnyCoder</h2><p className="text-lg md:text-xl text-[#86868b] font-normal">Create apps and websites by chatting with AI</p></div>273 unmodified lines274275276277278279280273 unmodified linesBuild with AnyCoder</h2><p className="text-lg md:text-xl text-[#86868b] font-normal">Create apps with AI</p></div>
backend_api.py+135
frontend/src/components/LandingPage.tsx+1-1