add redesign feature fix
Browse filesFiles changed (4)
239 unmodified lines2402412422432442451013 unmodified lines125912601261126212631264239 unmodified linesmetadata: Dict# Mock authentication for development# In production, integrate with HuggingFace OAuthclass MockAuth:1013 unmodified lines)@app.post("/api/import", response_model=ImportResponse)async def import_project(request: ImportRequest):"""239 unmodified lines2402412422432442452462472482492502512522532542552562572582591013 unmodified lines127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365239 unmodified linesmetadata: Dictclass PullRequestRequest(BaseModel):repo_id: str # username/space-namecode: strlanguage: strpr_title: Optional[str] = Nonepr_description: Optional[str] = Noneclass PullRequestResponse(BaseModel):success: boolmessage: strpr_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 modeif 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 tokentry:from backend_deploy import create_pull_request_on_spaceuser_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 requestsuccess, 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 messagesif "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:raiseexcept Exception as e:import tracebackerror_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 lines1133113411351132 unmodified linesexcept Exception as e:return False, f"Failed to list spaces: {str(e)}", None1132 unmodified lines1133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881132 unmodified linesexcept Exception as e:return False, f"Failed to list spaces: {str(e)}", Nonedef 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 codeArgs:repo_id: Full repo ID (username/space-name)code: New code to proposelanguage: Language/framework typetoken: HuggingFace API tokenpr_title: Title for the PR (default: "Redesign from AnyCoder")pr_description: Description for the PRReturns: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", Nonetry:api = HfApi(token=token)# Default PR title and descriptionif 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 experienceGenerated by [AnyCoder](https://huggingface.co/spaces/akhaliq/anycoder)"""# Create temporary directory for fileswith tempfile.TemporaryDirectory() as temp_dir:temp_path = Path(temp_dir)# Parse code based on languageif language == "transformers.js":try:files = parse_transformers_js_output(code)print(f"[PR] Parsed transformers.js files: {list(files.keys())}")# Write transformers.js filesfor filename, content in files.items():file_path = temp_path / filenamefile_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)}", Noneelif 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 parsedif 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_codeelif language == "react":files["app.tsx"] = cleaned_codeelse:files["app.py"] = cleaned_code# Write files (create subdirectories if needed)for filename, content in files.items():file_path = temp_path / filenamefile_path.parent.mkdir(parents=True, exist_ok=True)file_path.write_text(content, encoding='utf-8')# Generate requirements.txt if missing for Python appsif 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 filefiles = parse_multi_file_python_output(code)if not files:cleaned_code = remove_code_block(code)files['app.py'] = cleaned_codefor filename, content in files.items():file_path = temp_path / filenamefile_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=Truetry: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_infopr_url = commit_info.pr_url if hasattr(commit_info, 'pr_url') else Noneif not pr_url:# Fallback: construct PR URL from pr_num if availablepr_num = commit_info.pr_num if hasattr(commit_info, 'pr_num') else Noneif 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_urlexcept Exception as e:print(f"[PR] Error creating pull request: {e}")import tracebacktraceback.print_exc()return False, f"Failed to create pull request: {str(e)}", Noneexcept Exception as e:print(f"[PR] Top-level exception: {type(e).__name__}: {str(e)}")import tracebacktraceback.print_exc()return False, f"Pull request error: {str(e)}", None
66 unmodified lines676869707172216 unmodified lines289290291292293294295296297298299300301302303304305306307308309310323 unmodified lines63463563663763863964064164264364464510 unmodified lines65665765865966066166266366417 unmodified lines68268368468568668768884 unmodified lines77377477566 unmodified linesconst [redesignUrl, setRedesignUrl] = useState('');const [isRedesigning, setIsRedesigning] = useState(false);const [redesignError, setRedesignError] = useState('');// Debug effect for dropdown stateuseEffect(() => {216 unmodified linesconst result = await apiClient.importProject(redesignUrl);if (result.status === 'success') {// Import the code first, then trigger a redesignif (onImport && result.code) {onImport(result.code, result.language || 'html', redesignUrl);// Automatically trigger a redesign prompt after importsetTimeout(() => {const redesignPrompt = 'Make the app look better with minimal components needed and mobile friendly and modern design';onStart(redesignPrompt, result.language || 'html', selectedModel);}, 100);} else {// Fallback: trigger code generation with redesign contextconst 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);}setShowRedesignDialog(false);setRedesignUrl('');} else {setRedesignError(result.message || 'Failed to import project for redesign');}323 unmodified linessetShowImportDialog(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"><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></button>{/* Redesign Dialog */}10 unmodified linesonChange={(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"disabled={isRedesigning}/>{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</p></div></div>84 unmodified lines</div>);}66 unmodified lines67686970717273216 unmodified lines290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357323 unmodified lines68168268368468568668768868969069169269369469569669769810 unmodified lines70971071171271371471571671771871972072172272372472572672772872973073173217 unmodified lines75075175275375475575675775884 unmodified lines84384484584666 unmodified linesconst [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 stateuseEffect(() => {216 unmodified linesconst result = await apiClient.importProject(redesignUrl);if (result.status === 'success') {// Extract repo_id from URL for PR creationconst 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 itonImport(result.code, result.language || 'html', redesignUrl);// Send redesign prompt with code contextsetTimeout(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 generationconsole.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);setTimeout(() => {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 {setRedesignError('Missing required callbacks. Please try again.');}} else {setRedesignError(result.message || 'Failed to import project for redesign');}323 unmodified linessetShowImportDialog(false);setRedesignError('');}}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 linesonChange={(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-3"disabled={isRedesigning}/>{/* PR Option */}<label className="flex items-center gap-2 mb-3 cursor-pointer"><inputtype="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">{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 lines491492493494495496490 unmodified linesreturn response.data;}logout() {this.token = null;}490 unmodified lines491492493494495496497498499500501502503504505506507490 unmodified linesreturn 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