add redesign feature fix
Browse filesFiles changed (4)
239 unmodified lines2402412422432442452462472482492502512522532542552562572582591013 unmodified lines127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365239 unmodified lines metadata: Dict
class PullRequestRequest(BaseModel): repo_id: str # username/space-name code: str language: str pr_title: Optional[str] = None pr_description: Optional[str] = None
class PullRequestResponse(BaseModel): success: bool message: str pr_url: Optional[str] = None
# Mock authentication for development# In production, integrate with HuggingFace OAuthclass MockAuth:1013 unmodified lines )
@app.post("/api/create-pr", response_model=PullRequestResponse)async def create_pull_request( request: PullRequestRequest, authorization: Optional[str] = Header(None)): """Create a Pull Request on an existing HuggingFace Space with redesigned code""" print(f"[PR] ========== NEW PULL REQUEST ==========") print(f"[PR] Repo ID: {request.repo_id}") print(f"[PR] Language: {request.language}") print(f"[PR] PR Title: {request.pr_title}") auth = get_auth_from_header(authorization) if not auth.is_authenticated(): raise HTTPException(status_code=401, detail="Authentication required") # Check if this is dev mode if auth.token and auth.token.startswith("dev_token_"): return PullRequestResponse( success=False, message="Dev mode: PR creation not available in dev mode. Please use production authentication.", pr_url=None ) # Production mode with real OAuth token try: from backend_deploy import create_pull_request_on_space user_token = auth.token if auth.token else os.getenv("HF_TOKEN") if not user_token: raise HTTPException(status_code=401, detail="No HuggingFace token available. Please sign in first.") print(f"[PR] Creating PR with token (first 10 chars): {user_token[:10]}...") # Create the pull request success, message, pr_url = create_pull_request_on_space( repo_id=request.repo_id, code=request.code, language=request.language, token=user_token, pr_title=request.pr_title, pr_description=request.pr_description ) print(f"[PR] Result:") print(f"[PR] - Success: {success}") print(f"[PR] - Message: {message}") print(f"[PR] - PR URL: {pr_url}") if success: return PullRequestResponse( success=True, message=message, pr_url=pr_url ) else: # Provide user-friendly error messages if "401" in message or "Unauthorized" in message: raise HTTPException( status_code=401, detail="Authentication failed. Please sign in again with HuggingFace." ) elif "403" in message or "Forbidden" in message or "Permission" in message: raise HTTPException( status_code=403, detail="Permission denied. You may not have write access to this space." ) else: raise HTTPException( status_code=500, detail=message ) except HTTPException: raise except Exception as e: import traceback error_details = traceback.format_exc() print(f"[PR] Error: {error_details}") raise HTTPException( status_code=500, detail=f"Failed to create pull request: {str(e)}" )
@app.post("/api/import", response_model=ImportResponse)async def import_project(request: ImportRequest): """1132 unmodified lines1133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881132 unmodified lines except Exception as e: return False, f"Failed to list spaces: {str(e)}", None
def create_pull_request_on_space( repo_id: str, code: str, language: str, token: Optional[str] = None, pr_title: Optional[str] = None, pr_description: Optional[str] = None) -> Tuple[bool, str, Optional[str]]: """ Create a Pull Request on an existing HuggingFace Space with redesigned code Args: repo_id: Full repo ID (username/space-name) code: New code to propose language: Language/framework type token: HuggingFace API token pr_title: Title for the PR (default: "Redesign from AnyCoder") pr_description: Description for the PR Returns: Tuple of (success: bool, message: str, pr_url: Optional[str]) """ if not token: token = os.getenv("HF_TOKEN") if not token: return False, "No HuggingFace token provided", None try: api = HfApi(token=token) # Default PR title and description if not pr_title: pr_title = "🎨 Redesign from AnyCoder" if not pr_description: pr_description = """This Pull Request contains a redesigned version of the app with:
- ✨ Modern, mobile-friendly design- 🎯 Minimal, clean components- 📱 Responsive layout- 🚀 Improved user experience
Generated by [AnyCoder](https://huggingface.co/spaces/akhaliq/anycoder)""" # Create temporary directory for files with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir) # Parse code based on language if language == "transformers.js": try: files = parse_transformers_js_output(code) print(f"[PR] Parsed transformers.js files: {list(files.keys())}") # Write transformers.js files for filename, content in files.items(): file_path = temp_path / filename file_path.write_text(content, encoding='utf-8') except Exception as e: print(f"[PR] Error parsing transformers.js: {e}") return False, f"Error parsing transformers.js output: {str(e)}", None elif language == "html": html_code = parse_html_code(code) (temp_path / "index.html").write_text(html_code, encoding='utf-8') elif language == "comfyui": html_code = prettify_comfyui_json_for_html(code) (temp_path / "index.html").write_text(html_code, encoding='utf-8') elif language in ["gradio", "streamlit", "react"]: files = parse_multi_file_python_output(code) # Fallback if no files parsed if not files: print(f"[PR] No file markers found, using entire code as main file") cleaned_code = remove_code_block(code) if language == "streamlit": files["streamlit_app.py"] = cleaned_code elif language == "react": files["app.tsx"] = cleaned_code else: files["app.py"] = cleaned_code # Write files (create subdirectories if needed) for filename, content in files.items(): file_path = temp_path / filename file_path.parent.mkdir(parents=True, exist_ok=True) file_path.write_text(content, encoding='utf-8') # Generate requirements.txt if missing for Python apps if language in ["gradio", "streamlit"] and "requirements.txt" not in files: main_app = files.get('streamlit_app.py') or files.get('app.py', '') if main_app: print(f"[PR] Generating requirements.txt from imports") import_statements = extract_import_statements(main_app) requirements_content = generate_requirements_txt_with_llm(import_statements) (temp_path / "requirements.txt").write_text(requirements_content, encoding='utf-8') else: # Default: treat as code file files = parse_multi_file_python_output(code) if not files: cleaned_code = remove_code_block(code) files['app.py'] = cleaned_code for filename, content in files.items(): file_path = temp_path / filename file_path.parent.mkdir(parents=True, exist_ok=True) file_path.write_text(content, encoding='utf-8') # Upload files and create PR using create_commit with create_pr=True try: print(f"[PR] Creating pull request on {repo_id}") commit_info = api.upload_folder( folder_path=str(temp_path), repo_id=repo_id, repo_type="space", commit_message=pr_title, commit_description=pr_description, create_pr=True # This creates a PR instead of direct commit ) # Extract PR URL from commit_info pr_url = commit_info.pr_url if hasattr(commit_info, 'pr_url') else None if not pr_url: # Fallback: construct PR URL from pr_num if available pr_num = commit_info.pr_num if hasattr(commit_info, 'pr_num') else None if pr_num: pr_url = f"https://huggingface.co/spaces/{repo_id}/discussions/{pr_num}" else: pr_url = f"https://huggingface.co/spaces/{repo_id}/discussions" success_msg = f"✅ Pull Request created! View at: {pr_url}" print(f"[PR] {success_msg}") return True, success_msg, pr_url except Exception as e: print(f"[PR] Error creating pull request: {e}") import traceback traceback.print_exc() return False, f"Failed to create pull request: {str(e)}", None except Exception as e: print(f"[PR] Top-level exception: {type(e).__name__}: {str(e)}") import traceback traceback.print_exc() return False, f"Pull request error: {str(e)}", None
66 unmodified lines67686970717273216 unmodified lines290291292292293293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330295331332297298333334335336337338339340341342343344345346347348349350351352301302303353354305306307355356357323 unmodified lines68168268363768468568668768868969069169269369469569669769810 unmodified lines70971071165971271371471571671771871972072172272372472572672772872973073173217 unmodified lines75075175268575375475575675775884 unmodified lines84384484584666 unmodified lines const [redesignUrl, setRedesignUrl] = useState(''); const [isRedesigning, setIsRedesigning] = useState(false); const [redesignError, setRedesignError] = useState(''); const [createPR, setCreatePR] = useState(false); // Default to normal redesign (not PR)
// Debug effect for dropdown state useEffect(() => {216 unmodified lines const result = await apiClient.importProject(redesignUrl); if (result.status === 'success') { // Import the code first, then trigger a redesign if (onImport && result.code) { // Extract repo_id from URL for PR creation const spaceMatch = redesignUrl.match(/huggingface\.co\/spaces\/([^\/\s\)]+\/[^\/\s\)]+)/); const repoId = spaceMatch ? spaceMatch[1] : null; if (createPR && repoId && onImport && onStart) { // Option 1: Create a PR on the imported space // First, import and let AI redesign it onImport(result.code, result.language || 'html', redesignUrl); // Send redesign prompt with code context setTimeout(async () => { const redesignPrompt = `I have existing code in the editor that I imported from ${redesignUrl}. Please redesign it to make it look better with minimal components needed, mobile friendly, and modern design.
Current code:\`\`\`${result.language || 'html'}${result.code}\`\`\`
Please redesign this with:- Minimal, clean components- Mobile-first responsive design- Modern UI/UX best practices- Better visual hierarchy and spacing`; if (onStart) { onStart(redesignPrompt, result.language || 'html', selectedModel); } // Show info that PR will be created after code generation console.log('[Redesign] Will create PR after code generation completes'); }, 100); setShowRedesignDialog(false); setRedesignUrl(''); } else if (onImport && onStart) { // Option 2: Normal redesign flow (import and generate new code) onImport(result.code, result.language || 'html', redesignUrl); // Automatically trigger a redesign prompt after import setTimeout(() => { const redesignPrompt = 'Make the app look better with minimal components needed and mobile friendly and modern design'; onStart(redesignPrompt, result.language || 'html', selectedModel); const redesignPrompt = `I have existing code in the editor that I imported from ${redesignUrl}. Please redesign it to make it look better with minimal components needed, mobile friendly, and modern design.
Current code:\`\`\`${result.language || 'html'}${result.code}\`\`\`
Please redesign this with:- Minimal, clean components- Mobile-first responsive design- Modern UI/UX best practices- Better visual hierarchy and spacing`; if (onStart) { onStart(redesignPrompt, result.language || 'html', selectedModel); } }, 100); setShowRedesignDialog(false); setRedesignUrl(''); } else { // Fallback: trigger code generation with redesign context const redesignMessage = `Redesign this app from ${redesignUrl}: make the app look better with minimal components needed and mobile friendly and modern design`; onStart(redesignMessage, result.language || 'html', selectedModel); setRedesignError('Missing required callbacks. Please try again.'); } setShowRedesignDialog(false); setRedesignUrl(''); } else { setRedesignError(result.message || 'Failed to import project for redesign'); }323 unmodified lines setShowImportDialog(false); setRedesignError(''); }} className="px-3 py-1.5 bg-[#1d1d1f] text-[#f5f5f7] text-xs border border-[#424245] rounded-full hover:bg-[#2d2d2f] transition-all flex items-center gap-1.5 font-medium" className="relative px-3 py-1.5 bg-[#1d1d1f] text-[#f5f5f7] text-xs border border-[#424245] rounded-full hover:bg-[#2d2d2f] transition-all flex items-center gap-1.5 font-medium overflow-visible" > <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2.5}> <path strokeLinecap="round" strokeLinejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" /> </svg> <span>Redesign</span> {/* Enhanced NEW Badge with glow effect */} <span className="absolute -top-2 -right-2 px-2 py-0.5 bg-gradient-to-r from-pink-500 via-purple-500 to-indigo-500 text-white text-[9px] font-extrabold rounded-full shadow-lg animate-pulse"> <span className="relative z-10">NEW</span> {/* Glow effect */} <span className="absolute inset-0 bg-gradient-to-r from-pink-500 via-purple-500 to-indigo-500 rounded-full blur-sm opacity-75 animate-pulse"></span> </span> </button> {/* Redesign Dialog */}10 unmodified lines onChange={(e) => setRedesignUrl(e.target.value)} onKeyPress={(e) => e.key === 'Enter' && handleRedesignProject()} placeholder="https://huggingface.co/spaces/..." className="w-full px-3 py-2 rounded-lg text-xs bg-[#2d2d30] text-[#f5f5f7] border border-[#424245] focus:outline-none focus:border-white/50 font-normal mb-2" className="w-full px-3 py-2 rounded-lg text-xs bg-[#2d2d30] text-[#f5f5f7] border border-[#424245] focus:outline-none focus:border-white/50 font-normal mb-3" disabled={isRedesigning} /> {/* PR Option */} <label className="flex items-center gap-2 mb-3 cursor-pointer"> <input type="checkbox" checked={createPR} onChange={(e) => setCreatePR(e.target.checked)} disabled={isRedesigning} className="w-4 h-4 rounded bg-[#2d2d30] border-[#424245] text-white focus:ring-white focus:ring-offset-0" /> <span className="text-xs text-[#f5f5f7]"> Create Pull Request on original space </span> </label> {redesignError && ( <p className="text-xs text-red-400 mb-2">{redesignError}</p> )}17 unmodified lines </button> </div> <p className="text-[10px] text-[#86868b] mt-3"> Import and automatically redesign with modern, mobile-friendly design {createPR ? 'Creates a Pull Request on the original space with your redesign' : 'Import and automatically redesign with modern, mobile-friendly design'} </p> </div> </div>84 unmodified lines </div> );}
490 unmodified lines491492493494495496497498499500501502503504505506507490 unmodified lines return response.data; }
async createPullRequest(repoId: string, code: string, language: string, prTitle?: string, prDescription?: string): Promise<any> { const response = await this.client.post('/api/create-pr', { repo_id: repoId, code, language, pr_title: prTitle, pr_description: prDescription }); return response.data; }
logout() { this.token = null; }backend_api.py+101
backend_deploy.py+153
frontend/src/components/LandingPage.tsx+85-14
frontend/src/lib/api.ts+11