update
Browse filesFiles changed (4)
253 unmodified lines2542552562572582592602612622632642652662672682692702712721100 unmodified lines13731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473253 unmodified lines pr_url: Optional[str] = None
class DuplicateSpaceRequest(BaseModel): from_space_id: str # username/space-name to_space_name: Optional[str] = None # Just the name, not full ID private: bool = False
class DuplicateSpaceResponse(BaseModel): success: bool message: str space_url: Optional[str] = None space_id: Optional[str] = None
# Mock authentication for development# In production, integrate with HuggingFace OAuthclass MockAuth:1100 unmodified lines )
@app.post("/api/duplicate-space", response_model=DuplicateSpaceResponse)async def duplicate_space_endpoint( request: DuplicateSpaceRequest, authorization: Optional[str] = Header(None)): """Duplicate a HuggingFace Space to the user's account""" print(f"[Duplicate] ========== DUPLICATE SPACE REQUEST ==========") print(f"[Duplicate] From: {request.from_space_id}") print(f"[Duplicate] To: {request.to_space_name or 'auto'}") print(f"[Duplicate] Private: {request.private}") 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 DuplicateSpaceResponse( success=False, message="Dev mode: Space duplication not available in dev mode. Please use production authentication.", space_url=None, space_id=None ) # Production mode with real OAuth token try: from backend_deploy import duplicate_space_to_user 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"[Duplicate] Duplicating space with token (first 10 chars): {user_token[:10]}...") # Duplicate the space success, message, space_url = duplicate_space_to_user( from_space_id=request.from_space_id, to_space_name=request.to_space_name, token=user_token, private=request.private ) print(f"[Duplicate] Result:") print(f"[Duplicate] - Success: {success}") print(f"[Duplicate] - Message: {message}") print(f"[Duplicate] - Space URL: {space_url}") if success: # Extract space_id from URL space_id = space_url.split("/spaces/")[-1] if space_url else None return DuplicateSpaceResponse( success=True, message=message, space_url=space_url, space_id=space_id ) 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 access to this space." ) elif "404" in message or "not found" in message.lower(): raise HTTPException( status_code=404, detail="Space not found. Please check the URL and try again." ) else: raise HTTPException( status_code=500, detail=message ) except HTTPException: raise except Exception as e: import traceback error_details = traceback.format_exc() print(f"[Duplicate] Error: {error_details}") raise HTTPException( status_code=500, detail=f"Failed to duplicate space: {str(e)}" )
@app.post("/api/import", response_model=ImportResponse)async def import_project(request: ImportRequest): """1133 unmodified lines11341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091133 unmodified lines return False, f"Failed to list spaces: {str(e)}", None
def duplicate_space_to_user( from_space_id: str, to_space_name: Optional[str] = None, token: Optional[str] = None, private: bool = False) -> Tuple[bool, str, Optional[str]]: """ Duplicate a HuggingFace Space to the user's account Args: from_space_id: Source space ID (username/space-name) to_space_name: Destination space name (just the name, not full ID) token: HuggingFace API token private: Whether the duplicated space should be private Returns: Tuple of (success: bool, message: str, space_url: Optional[str]) """ if not token: token = os.getenv("HF_TOKEN") if not token: return False, "No HuggingFace token provided", None try: from huggingface_hub import duplicate_space # Get username from token api = HfApi(token=token) user_info = api.whoami() username = user_info.get("name") or user_info.get("preferred_username") or "user" # If no destination name provided, use original name if not to_space_name: # Extract original space name original_name = from_space_id.split('/')[-1] to_space_name = original_name # Clean space name to_space_name = re.sub(r'[^a-z0-9-]', '-', to_space_name.lower()) to_space_name = re.sub(r'-+', '-', to_space_name).strip('-') # Construct full destination ID to_space_id = f"{username}/{to_space_name}" print(f"[Duplicate] Duplicating {from_space_id} to {to_space_id}") # Duplicate the space duplicated_repo = duplicate_space( from_id=from_space_id, to_id=to_space_name, # Just the name, not full ID token=token, private=private, exist_ok=True ) # Extract space URL space_url = f"https://huggingface.co/spaces/{to_space_id}" success_msg = f"✅ Space duplicated! View at: {space_url}" print(f"[Duplicate] {success_msg}") return True, success_msg, space_url except Exception as e: print(f"[Duplicate] Error: {type(e).__name__}: {str(e)}") import traceback traceback.print_exc() return False, f"Failed to duplicate space: {str(e)}", None
def create_pull_request_on_space( repo_id: str, code: str,245 unmodified lines24624724824924925025125125225325425525225325425525625725825926026126226326426526626726826927027125725825927227326126226327427527627727827928028128228328428528628728826528929029129229318 unmodified lines31231331431531631731831932032132232332432532632729229329429529629729829932832933033133233333433533633733833934015 unmodified lines3563573583213593603613623633643653663673683693703713723733743753763283293303313323333773783793803813823833843855 unmodified lines391392393394345346347348395396397398399400401402403353404405355356406407408360409410411412245 unmodified lines setImportError('');
try { const result = await apiClient.importProject(importUrl); // Extract space ID from URL for duplication const spaceMatch = importUrl.match(/huggingface\.co\/spaces\/([^\/\s\)]+\/[^\/\s\)]+)/); if (result.status === 'success') { // Use onImport if available (better UX - directly loads code) // Otherwise fall back to onStart (sends message to generate) if (onImport && result.code) { onImport(result.code, result.language || 'html', importUrl); if (spaceMatch) { // This is a HuggingFace Space - duplicate it const fromSpaceId = spaceMatch[1]; console.log('[Import] Duplicating space:', fromSpaceId); const duplicateResult = await apiClient.duplicateSpace(fromSpaceId); if (duplicateResult.success) { // Show success message with link to duplicated space alert(`✅ Space duplicated successfully!\n\nView your space: ${duplicateResult.space_url}`); // Also load the code in the editor const importResult = await apiClient.importProject(importUrl); if (importResult.status === 'success' && onImport && importResult.code) { onImport(importResult.code, importResult.language || 'html', duplicateResult.space_url); } setShowImportDialog(false); setImportUrl(''); } else { // Fallback: trigger code generation with import context const importMessage = `Imported from ${importUrl}`; onStart(importMessage, result.language || 'html', selectedModel); setImportError(duplicateResult.message || 'Failed to duplicate space'); } setShowImportDialog(false); setImportUrl(''); } else { // Not a Space URL - fall back to regular import const result = await apiClient.importProject(importUrl); if (result.status === 'success') { if (onImport && result.code) { onImport(result.code, result.language || 'html', importUrl); } else { const importMessage = `Imported from ${importUrl}`; onStart(importMessage, result.language || 'html', selectedModel); } setShowImportDialog(false); setImportUrl(''); } else { setImportError(result.message || 'Failed to import project'); setImportError(result.message || 'Failed to import project'); } } } catch (error: any) { console.error('Import error:', error);18 unmodified lines setRedesignError('');
try { // Extract space ID from URL const spaceMatch = redesignUrl.match(/huggingface\.co\/spaces\/([^\/\s\)]+\/[^\/\s\)]+)/); const repoId = spaceMatch ? spaceMatch[1] : null; if (!repoId) { setRedesignError('Please enter a valid HuggingFace Space URL'); setIsRedesigning(false); return; } // Import the code first const result = await apiClient.importProject(redesignUrl); if (result.status === 'success') { // 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 if (result.status !== 'success') { setRedesignError(result.message || 'Failed to import project for redesign'); setIsRedesigning(false); return; } if (createPR) { // Option 1: Create a PR on the original space // Import code and let AI redesign it if (onImport && onStart) { onImport(result.code, result.language || 'html', redesignUrl); // Send redesign prompt with code context15 unmodified lines 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 { setRedesignError('Missing required callbacks. Please try again.'); } } else { // Option 2: Duplicate the space and then apply redesign console.log('[Redesign] Duplicating space for redesign:', repoId); const duplicateResult = await apiClient.duplicateSpace(repoId); if (duplicateResult.success) { // Show success message alert(`✅ Space duplicated successfully!\n\nYour space: ${duplicateResult.space_url}\n\nNow generating redesign...`); } 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. // Load the code and trigger redesign if (onImport && onStart) { onImport(result.code, result.language || 'html', duplicateResult.space_url); setTimeout(() => { const redesignPrompt = `I have existing code in the editor that I duplicated from ${redesignUrl}. Please redesign it to make it look better with minimal components needed, mobile friendly, and modern design.
Current code:\`\`\`${result.language || 'html'}5 unmodified lines- Mobile-first responsive design- Modern UI/UX best practices- Better visual hierarchy and spacing`; if (onStart) { onStart(redesignPrompt, result.language || 'html', selectedModel); } }, 100); if (onStart) { onStart(redesignPrompt, result.language || 'html', selectedModel); } }, 100); } setShowRedesignDialog(false); setRedesignUrl(''); } else { setRedesignError('Missing required callbacks. Please try again.'); setRedesignError(duplicateResult.message || 'Failed to duplicate space'); } } else { setRedesignError(result.message || 'Failed to import project for redesign'); } } catch (error: any) { console.error('Redesign error:', error); setRedesignError(error.response?.data?.message || error.message || 'Failed to import project for redesign'); setRedesignError(error.response?.data?.message || error.message || 'Failed to process redesign request'); } finally { setIsRedesigning(false); }501 unmodified lines502503504505506507508509510511512513514515516501 unmodified lines return response.data; }
async duplicateSpace(fromSpaceId: string, toSpaceName?: string, isPrivate: boolean = false): Promise<any> { const response = await this.client.post('/api/duplicate-space', { from_space_id: fromSpaceId, to_space_name: toSpaceName, private: isPrivate }); return response.data; }
logout() { this.token = null; }backend_api.py+108
backend_deploy.py+70
frontend/src/components/LandingPage.tsx+85-36
frontend/src/lib/api.ts+9