update
Browse filesFiles changed (4)
253 unmodified lines2542552562572582591100 unmodified lines136013611362136313641365253 unmodified linespr_url: Optional[str] = None# Mock authentication for development# In production, integrate with HuggingFace OAuthclass MockAuth:1100 unmodified lines)@app.post("/api/import", response_model=ImportResponse)async def import_project(request: ImportRequest):"""253 unmodified lines2542552562572582592602612622632642652662672682692702712721100 unmodified lines13731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473253 unmodified linespr_url: Optional[str] = Noneclass DuplicateSpaceRequest(BaseModel):from_space_id: str # username/space-nameto_space_name: Optional[str] = None # Just the name, not full IDprivate: bool = Falseclass DuplicateSpaceResponse(BaseModel):success: boolmessage: strspace_url: Optional[str] = Nonespace_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 modeif 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 tokentry:from backend_deploy import duplicate_space_to_useruser_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 spacesuccess, 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 URLspace_id = space_url.split("/spaces/")[-1] if space_url else Nonereturn DuplicateSpaceResponse(success=True,message=message,space_url=space_url,space_id=space_id)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 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:raiseexcept Exception as e:import tracebackerror_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 lines1134113511361137113811391133 unmodified linesreturn False, f"Failed to list spaces: {str(e)}", Nonedef create_pull_request_on_space(repo_id: str,code: str,1133 unmodified lines11341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091133 unmodified linesreturn False, f"Failed to list spaces: {str(e)}", Nonedef 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 accountArgs:from_space_id: Source space ID (username/space-name)to_space_name: Destination space name (just the name, not full ID)token: HuggingFace API tokenprivate: Whether the duplicated space should be privateReturns: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", Nonetry:from huggingface_hub import duplicate_space# Get username from tokenapi = 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 nameif not to_space_name:# Extract original space nameoriginal_name = from_space_id.split('/')[-1]to_space_name = original_name# Clean space nameto_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 IDto_space_id = f"{username}/{to_space_name}"print(f"[Duplicate] Duplicating {from_space_id} to {to_space_id}")# Duplicate the spaceduplicated_repo = duplicate_space(from_id=from_space_id,to_id=to_space_name, # Just the name, not full IDtoken=token,private=private,exist_ok=True)# Extract space URLspace_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_urlexcept Exception as e:print(f"[Duplicate] Error: {type(e).__name__}: {str(e)}")import tracebacktraceback.print_exc()return False, f"Failed to duplicate space: {str(e)}", Nonedef create_pull_request_on_space(repo_id: str,code: str,
245 unmodified lines24624724824925025125225325425525625725825926026126226326426526626726818 unmodified lines28728828929029129229329429529629729829930030130215 unmodified lines3183193203213223233243253263273283293303313323333343353365 unmodified lines342343344345346347348349350351352353354355356357358359360361362363245 unmodified linessetImportError('');try {const result = await apiClient.importProject(importUrl);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);} else {// Fallback: trigger code generation with import contextconst importMessage = `Imported from ${importUrl}`;onStart(importMessage, result.language || 'html', selectedModel);}setShowImportDialog(false);setImportUrl('');} else {setImportError(result.message || 'Failed to import project');}} catch (error: any) {console.error('Import error:', error);18 unmodified linessetRedesignError('');try {const 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 context15 unmodified linesonStart(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'}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);setShowRedesignDialog(false);setRedesignUrl('');} else {setRedesignError('Missing required callbacks. Please try again.');}} 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');} finally {setIsRedesigning(false);}245 unmodified lines24624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229318 unmodified lines31231331431531631731831932032132232332432532632732832933033133233333433533633733833934015 unmodified lines3563573583593603613623633643653663673683693703713723733743753763773783793803813823833843855 unmodified lines391392393394395396397398399400401402403404405406407408409410411412245 unmodified linessetImportError('');try {// Extract space ID from URL for duplicationconst spaceMatch = importUrl.match(/huggingface\.co\/spaces\/([^\/\s\)]+\/[^\/\s\)]+)/);if (spaceMatch) {// This is a HuggingFace Space - duplicate itconst 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 spacealert(`✅ Space duplicated successfully!\n\nView your space: ${duplicateResult.space_url}`);// Also load the code in the editorconst 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 {setImportError(duplicateResult.message || 'Failed to duplicate space');}} else {// Not a Space URL - fall back to regular importconst 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');}}} catch (error: any) {console.error('Import error:', error);18 unmodified linessetRedesignError('');try {// Extract space ID from URLconst 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 firstconst result = await apiClient.importProject(redesignUrl);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 itif (onImport && onStart) {onImport(result.code, result.language || 'html', redesignUrl);// Send redesign prompt with code context15 unmodified linesonStart(redesignPrompt, result.language || 'html', selectedModel);}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 redesignconsole.log('[Redesign] Duplicating space for redesign:', repoId);const duplicateResult = await apiClient.duplicateSpace(repoId);if (duplicateResult.success) {// Show success messagealert(`✅ Space duplicated successfully!\n\nYour space: ${duplicateResult.space_url}\n\nNow generating redesign...`);// Load the code and trigger redesignif (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);}setShowRedesignDialog(false);setRedesignUrl('');} else {setRedesignError(duplicateResult.message || 'Failed to duplicate space');}}} catch (error: any) {console.error('Redesign error:', error);setRedesignError(error.response?.data?.message || error.message || 'Failed to process redesign request');} finally {setIsRedesigning(false);}
501 unmodified lines502503504505506507501 unmodified linesreturn response.data;}logout() {this.token = null;}501 unmodified lines502503504505506507508509510511512513514515516501 unmodified linesreturn 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