add import feature
Browse filesFiles changed (6)
27 unmodified lines282930313233343536111 unmodified lines148149150151152153154155156157158159160161162163164165166167487 unmodified lines65565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375427 unmodified lines is_mistral_model)
# Import project importer for importing from HF/GitHubfrom project_importer import ProjectImporter
# Import system prompts from standalone backend_prompts.py# No dependencies on Gradio or heavy librariesprint("[Startup] Loading system prompts from backend_prompts...")111 unmodified lines status: str
class ImportRequest(BaseModel): url: str prefer_local: bool = False
class ImportResponse(BaseModel): status: str message: str code: str language: str url: str metadata: Dict
# Mock authentication for development# In production, integrate with HuggingFace OAuthclass MockAuth:487 unmodified lines )
@app.post("/api/import", response_model=ImportResponse)async def import_project(request: ImportRequest): """ Import a project from HuggingFace Space, HuggingFace Model, or GitHub repo Supports URLs like: - https://huggingface.co/spaces/username/space-name - https://huggingface.co/username/model-name - https://github.com/username/repo-name """ try: importer = ProjectImporter() result = importer.import_from_url(request.url) # Handle model-specific prefer_local flag if request.prefer_local and result.get('metadata', {}).get('has_alternatives'): # Switch to local code if available local_code = result['metadata'].get('local_code') if local_code: result['code'] = local_code result['metadata']['code_type'] = 'local' result['message'] = result['message'].replace('inference', 'local') return ImportResponse(**result) except Exception as e: return ImportResponse( status="error", message=f"Import failed: {str(e)}", code="", language="unknown", url=request.url, metadata={} )
@app.get("/api/import/space/{username}/{space_name}")async def import_space(username: str, space_name: str): """Import a specific HuggingFace Space by username and space name""" try: importer = ProjectImporter() result = importer.import_space(username, space_name) return result except Exception as e: return { "status": "error", "message": f"Failed to import space: {str(e)}", "code": "", "language": "unknown", "url": f"https://huggingface.co/spaces/{username}/{space_name}", "metadata": {} }
@app.get("/api/import/model/{path:path}")async def import_model(path: str, prefer_local: bool = False): """ Import a specific HuggingFace Model by model ID Example: /api/import/model/meta-llama/Llama-3.2-1B-Instruct """ try: importer = ProjectImporter() result = importer.import_model(path, prefer_local=prefer_local) return result except Exception as e: return { "status": "error", "message": f"Failed to import model: {str(e)}", "code": "", "language": "python", "url": f"https://huggingface.co/{path}", "metadata": {} }
@app.get("/api/import/github/{owner}/{repo}")async def import_github(owner: str, repo: str): """Import a GitHub repository by owner and repo name""" try: importer = ProjectImporter() result = importer.import_github_repo(owner, repo) return result except Exception as e: return { "status": "error", "message": f"Failed to import repository: {str(e)}", "code": "", "language": "python", "url": f"https://github.com/{owner}/{repo}", "metadata": {} }
@app.websocket("/ws/generate")async def websocket_generate(websocket: WebSocket): """WebSocket endpoint for real-time code generation"""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166"""Example usage of the ProjectImporter module
This script demonstrates how to use the standalone project importerto fetch code from various sources without Gradio."""
import sysimport os
# Add parent directory to pathsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from project_importer import ProjectImporter
def example_import_space(): """Example: Import a HuggingFace Space""" print("=" * 80) print("Example 1: Importing a HuggingFace Space") print("=" * 80) importer = ProjectImporter() result = importer.import_space("akhaliq", "anycoder") print(f"Status: {result['status']}") print(f"Message: {result['message']}") print(f"Language: {result['language']}") print(f"Files: {len(result['metadata'].get('files', []))}") print(f"\nFirst 500 characters of code:\n{result['code'][:500]}...") print()
def example_import_model(): """Example: Import a HuggingFace Model""" print("=" * 80) print("Example 2: Importing a HuggingFace Model") print("=" * 80) importer = ProjectImporter() result = importer.import_model("meta-llama/Llama-3.2-1B-Instruct") print(f"Status: {result['status']}") print(f"Message: {result['message']}") print(f"Language: {result['language']}") print(f"Pipeline Tag: {result['metadata'].get('pipeline_tag')}") print(f"\nCode:\n{result['code']}") print()
def example_import_github(): """Example: Import a GitHub Repository""" print("=" * 80) print("Example 3: Importing from GitHub") print("=" * 80) importer = ProjectImporter() result = importer.import_github_repo("huggingface", "transformers") print(f"Status: {result['status']}") print(f"Message: {result['message']}") print(f"Language: {result['language']}") print(f"\nFirst 500 characters of code:\n{result['code'][:500]}...") print()
def example_import_from_url(): """Example: Import from any URL""" print("=" * 80) print("Example 4: Import from URL (automatic detection)") print("=" * 80) importer = ProjectImporter() # Test different URL types urls = [ "https://huggingface.co/spaces/akhaliq/anycoder", "https://huggingface.co/meta-llama/Llama-3.2-1B-Instruct", "https://github.com/huggingface/diffusers" ] for url in urls: print(f"\nImporting: {url}") result = importer.import_from_url(url) print(f" Status: {result['status']}") print(f" Language: {result['language']}") print(f" Message: {result['message']}")
def example_save_to_file(): """Example: Save imported code to a file""" print("=" * 80) print("Example 5: Save imported code to file") print("=" * 80) importer = ProjectImporter() result = importer.import_model("stabilityai/stable-diffusion-3.5-large") if result['status'] == 'success': output_file = "imported_sd3.5_code.py" with open(output_file, 'w', encoding='utf-8') as f: f.write(result['code']) print(f"Code saved to: {output_file}") else: print(f"Failed to import: {result['message']}") print()
def example_with_metadata(): """Example: Working with metadata""" print("=" * 80) print("Example 6: Working with metadata") print("=" * 80) importer = ProjectImporter() result = importer.import_model("Qwen/Qwen2.5-Coder-32B-Instruct") print(f"Status: {result['status']}") print(f"Message: {result['message']}") print(f"\nMetadata:") for key, value in result['metadata'].items(): print(f" {key}: {value}") # Check if there are alternatives if result['metadata'].get('has_alternatives'): print("\n✨ This model has multiple code options available!") print(" - Inference code (serverless)") print(" - Local code (transformers/diffusers)") print()
def main(): """Run all examples""" print("\n🚀 ProjectImporter Examples\n") try: example_import_space() except Exception as e: print(f"❌ Space import failed: {e}\n") try: example_import_model() except Exception as e: print(f"❌ Model import failed: {e}\n") try: example_import_github() except Exception as e: print(f"❌ GitHub import failed: {e}\n") try: example_import_from_url() except Exception as e: print(f"❌ URL import failed: {e}\n") try: example_with_metadata() except Exception as e: print(f"❌ Metadata example failed: {e}\n") print("\n✅ Examples completed!")
if __name__ == "__main__": main()
175 unmodified lines17617717817918018118218318418518618718818919019119219319419519619781 unmodified lines279280281282283284285175 unmodified lines } };
const handleImport = (code: string, language: Language) => { setGeneratedCode(code); setSelectedLanguage(language); // Add a system message const importMessage: Message = { role: 'assistant', content: `✅ Project imported successfully! Language: ${language}`, timestamp: new Date().toISOString(), }; setMessages((prev) => [...prev, importMessage]); // Switch to editor view on mobile setMobileView('editor'); };
return ( <div className="h-screen flex flex-col bg-[#1d1d1f]"> <Header />81 unmodified lines onModelChange={setSelectedModel} onDeploy={handleDeploy} onClear={handleClear} onImport={handleImport} isGenerating={isGenerating} /> </div>10 unmodified lines111213141516174 unmodified lines2223242526272829303132333435363727 unmodified lines656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510655 unmodified lines16216316416516616716816917017117217317417516 unmodified lines19219319419519619714719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825910 unmodified lines onModelChange: (modelId: string) => void; onDeploy: () => void; onClear: () => void; onImport?: (code: string, language: Language) => void; isGenerating: boolean;}
4 unmodified lines onModelChange, onDeploy, onClear, onImport, isGenerating,}: ControlPanelProps) { const [models, setModels] = useState<Model[]>([]); const [languages, setLanguages] = useState<Language[]>([]); const [isLoading, setIsLoading] = useState(true); const [showImportModal, setShowImportModal] = useState(false); const [importUrl, setImportUrl] = useState(''); const [isImporting, setIsImporting] = useState(false); const [importError, setImportError] = useState<string | null>(null);
useEffect(() => { loadData();27 unmodified lines } };
const handleImport = async () => { if (!importUrl.trim()) { setImportError('Please enter a valid URL'); return; }
setIsImporting(true); setImportError(null);
try { console.log('Importing from:', importUrl); const result = await apiClient.importProject(importUrl); if (result.status === 'success') { console.log('Import successful:', result); // Call the onImport callback if provided if (onImport && result.code) { onImport(result.code, result.language || 'html'); } // Close modal and reset setShowImportModal(false); setImportUrl(''); setImportError(null); } else { setImportError(result.message || 'Import failed'); } } catch (error: any) { console.error('Import error:', error); setImportError(error.response?.data?.message || error.message || 'Failed to import project'); } finally { setIsImporting(false); } };
return ( <div className="bg-[#28282a] p-5 space-y-6 h-full"> <h3 className="text-base font-semibold text-[#e5e5e7] tracking-tight mb-2">Configuration</h3>55 unmodified lines
{/* Action Buttons */} <div className="flex flex-col space-y-3 pt-4"> <button onClick={() => setShowImportModal(true)} disabled={isGenerating} className="w-full px-4 py-3.5 bg-[#34c759] text-white text-sm rounded-xl hover:bg-[#30b350] disabled:opacity-50 disabled:cursor-not-allowed transition-all font-semibold flex items-center justify-center space-x-2 shadow-md active:scale-95" > <span>📥</span> <span>Import Project</span> </button> <button onClick={onDeploy} disabled={isGenerating}16 unmodified lines <div className="mt-6 p-4 bg-[#2c2c2e] border border-[#48484a] rounded-xl shadow-sm"> <h4 className="text-sm font-semibold text-[#e5e5e7] mb-3 tracking-tight">💡 Tips</h4> <ul className="text-xs text-[#86868b] space-y-2 leading-relaxed"> <li>• Import projects from HF/GitHub</li> <li>• Be specific in your requirements</li> <li>• Try different AI models</li> <li>• Edit code in the editor</li> <li>• Deploy to HF Spaces</li> </ul> </div>
{/* Import Modal */} {showImportModal && ( <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"> <div className="bg-[#2c2c2e] border border-[#48484a] rounded-2xl p-6 max-w-md w-full shadow-2xl"> <h3 className="text-lg font-semibold text-[#e5e5e7] mb-4 tracking-tight">📥 Import Project</h3> <div className="space-y-4"> <div> <label className="block text-sm font-medium text-[#e5e5e7] mb-2"> Project URL </label> <input type="text" value={importUrl} onChange={(e) => setImportUrl(e.target.value)} placeholder="https://huggingface.co/spaces/..." disabled={isImporting} className="w-full px-4 py-3 bg-[#3a3a3c] text-[#e5e5e7] text-sm border border-[#48484a] rounded-xl focus:outline-none focus:ring-2 focus:ring-[#34c759] focus:border-transparent disabled:opacity-50 placeholder-[#86868b] font-medium" onKeyDown={(e) => e.key === 'Enter' && handleImport()} /> <p className="text-xs text-[#86868b] mt-2"> Supported: HF Spaces, HF Models, GitHub repos </p> </div>
{importError && ( <div className="p-3 bg-[#ff3b30] bg-opacity-10 border border-[#ff3b30] rounded-xl"> <p className="text-sm text-[#ff3b30]">{importError}</p> </div> )}
<div className="flex space-x-3"> <button onClick={handleImport} disabled={isImporting || !importUrl.trim()} className="flex-1 px-4 py-3 bg-[#34c759] text-white text-sm rounded-xl hover:bg-[#30b350] disabled:opacity-50 disabled:cursor-not-allowed transition-all font-semibold active:scale-95" > {isImporting ? '⏳ Importing...' : '✓ Import'} </button> <button onClick={() => { setShowImportModal(false); setImportUrl(''); setImportError(null); }} disabled={isImporting} className="flex-1 px-4 py-3 bg-[#3a3a3c] text-[#e5e5e7] text-sm rounded-xl hover:bg-[#48484a] disabled:opacity-50 disabled:cursor-not-allowed transition-all font-semibold border border-[#48484a] active:scale-95" > Cancel </button> </div> </div> </div> </div> )} </div> );}195 unmodified lines196197198199200201202203204205206207208209210211212213214215216217218219220221222223195 unmodified lines return response.data; }
async importProject(url: string, preferLocal: boolean = false): Promise<any> { const response = await this.client.post('/api/import', { url, prefer_local: preferLocal }); return response.data; }
async importSpace(username: string, spaceName: string): Promise<any> { const response = await this.client.get(`/api/import/space/${username}/${spaceName}`); return response.data; }
async importModel(modelId: string, preferLocal: boolean = false): Promise<any> { const response = await this.client.get(`/api/import/model/${modelId}`, { params: { prefer_local: preferLocal } }); return response.data; }
async importGithub(owner: string, repo: string): Promise<any> { const response = await this.client.get(`/api/import/github/${owner}/${repo}`); return response.data; }
logout() { this.token = null; }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682"""Project Importer - Standalone module for importing projects from various sources
This module provides functionality to import projects from:- HuggingFace Spaces- HuggingFace Models- GitHub Repositories
No Gradio dependency required - pure Python implementation."""
import osimport reimport requestsfrom typing import Dict, List, Optional, Tuplefrom urllib.parse import urlparsefrom huggingface_hub import HfApi, list_repo_files
class ProjectImporter: """Main class for importing projects from various sources""" def __init__(self, hf_token: Optional[str] = None): """ Initialize the ProjectImporter. Args: hf_token: Optional HuggingFace token for authenticated requests """ self.hf_token = hf_token or os.environ.get("HF_TOKEN") self.api = HfApi(token=self.hf_token) def import_from_url(self, url: str) -> Dict[str, any]: """ Import a project from any supported URL. Args: url: URL to import from (HF Space, HF Model, or GitHub) Returns: Dictionary containing: - status: Success/error message - code: Extracted code content - language: Detected language/framework - url: Original URL - metadata: Additional metadata """ if not url or not url.strip(): return { "status": "error", "message": "Please provide a valid URL", "code": "", "language": "unknown", "url": url, "metadata": {} } # Parse URL to determine source type kind, meta = self._parse_url(url) if kind == "hf_space": return self.import_space(meta["username"], meta["project"]) elif kind == "hf_model": return self.import_model(meta["repo_id"]) elif kind == "github": return self.import_github_repo(meta["owner"], meta["repo"]) else: return { "status": "error", "message": "Unsupported URL format. Supported: HF Spaces, HF Models, GitHub repos", "code": "", "language": "unknown", "url": url, "metadata": {} } def import_space(self, username: str, project_name: str) -> Dict[str, any]: """ Import a HuggingFace Space. Args: username: HuggingFace username project_name: Space name Returns: Dictionary with imported project data """ try: space_id = f"{username}/{project_name}" space_info = self.api.space_info(space_id) # Detect if this is a transformers.js space if space_info.sdk == "static" and self._is_transformers_js_space(username, project_name): code, files = self._fetch_transformers_js_files(username, project_name) return { "status": "success", "message": f"Successfully imported transformers.js space: {space_id}", "code": code, "language": "transformers.js", "url": f"https://huggingface.co/spaces/{space_id}", "metadata": { "sdk": "static", "type": "transformers.js", "files": files } } # Handle multi-file spaces files = self._fetch_all_space_files(username, project_name, space_info.sdk) if files: code = self._format_multi_file_content(files, username, project_name, space_info.sdk) language = self._detect_language_from_sdk(space_info.sdk) return { "status": "success", "message": f"Successfully imported space: {space_id}", "code": code, "language": language, "url": f"https://huggingface.co/spaces/{space_id}", "metadata": { "sdk": space_info.sdk, "files": list(files.keys()) } } else: # Fallback to single file main_file, content = self._fetch_main_file(username, project_name, space_info.sdk) if content: return { "status": "success", "message": f"Successfully imported space: {space_id}", "code": content, "language": self._detect_language_from_sdk(space_info.sdk), "url": f"https://huggingface.co/spaces/{space_id}", "metadata": { "sdk": space_info.sdk, "main_file": main_file } } else: return { "status": "error", "message": f"Could not find main file in space {space_id}", "code": "", "language": "unknown", "url": f"https://huggingface.co/spaces/{space_id}", "metadata": {"sdk": space_info.sdk} } except Exception as e: return { "status": "error", "message": f"Failed to import space: {str(e)}", "code": "", "language": "unknown", "url": f"https://huggingface.co/spaces/{username}/{project_name}", "metadata": {} } def import_model(self, model_id: str, prefer_local: bool = False) -> Dict[str, any]: """ Import a HuggingFace Model. Args: model_id: HuggingFace model ID (e.g., "meta-llama/Llama-2-7b") prefer_local: If True, prefer local inference code over serverless Returns: Dictionary with imported model data """ try: # Get model info model_info = self.api.model_info(model_id) pipeline_tag = getattr(model_info, "pipeline_tag", None) # Try to get inference provider code inference_code = self._generate_inference_code(model_id, pipeline_tag) # Try to get transformers/diffusers code from README readme_code = None try: readme = self._fetch_hf_model_readme(model_id) if readme: _, readme_code = self._extract_code_from_markdown(readme) except: pass # Determine which code to return if inference_code and readme_code: code = readme_code if prefer_local else inference_code code_type = "local" if prefer_local else "inference" return { "status": "success", "message": f"Successfully imported model: {model_id} ({code_type} code)", "code": code, "language": "python", "url": f"https://huggingface.co/{model_id}", "metadata": { "pipeline_tag": pipeline_tag, "code_type": code_type, "has_alternatives": True, "inference_code": inference_code, "local_code": readme_code } } elif inference_code: return { "status": "success", "message": f"Successfully imported model: {model_id} (inference code)", "code": inference_code, "language": "python", "url": f"https://huggingface.co/{model_id}", "metadata": { "pipeline_tag": pipeline_tag, "code_type": "inference" } } elif readme_code: return { "status": "success", "message": f"Successfully imported model: {model_id} (local code)", "code": readme_code, "language": "python", "url": f"https://huggingface.co/{model_id}", "metadata": { "pipeline_tag": pipeline_tag, "code_type": "local" } } else: return { "status": "error", "message": f"No code found for model: {model_id}", "code": "", "language": "python", "url": f"https://huggingface.co/{model_id}", "metadata": {"pipeline_tag": pipeline_tag} } except Exception as e: return { "status": "error", "message": f"Failed to import model: {str(e)}", "code": "", "language": "python", "url": f"https://huggingface.co/{model_id}", "metadata": {} } def import_github_repo(self, owner: str, repo: str) -> Dict[str, any]: """ Import a GitHub repository. Args: owner: GitHub username/organization repo: Repository name Returns: Dictionary with imported repository data """ try: readme = self._fetch_github_readme(owner, repo) if not readme: return { "status": "error", "message": f"Could not fetch README from {owner}/{repo}", "code": "", "language": "python", "url": f"https://github.com/{owner}/{repo}", "metadata": {} } lang, code = self._extract_code_from_markdown(readme) if code: return { "status": "success", "message": f"Successfully imported code from {owner}/{repo}", "code": code, "language": lang or "python", "url": f"https://github.com/{owner}/{repo}", "metadata": { "source": "github", "detected_language": lang } } else: return { "status": "error", "message": f"No relevant code found in README of {owner}/{repo}", "code": "", "language": "python", "url": f"https://github.com/{owner}/{repo}", "metadata": {} } except Exception as e: return { "status": "error", "message": f"Failed to import repository: {str(e)}", "code": "", "language": "python", "url": f"https://github.com/{owner}/{repo}", "metadata": {} } # ==================== Private Helper Methods ==================== def _parse_url(self, url: str) -> Tuple[str, Optional[Dict]]: """Parse URL and detect source type""" try: parsed = urlparse(url.strip()) netloc = (parsed.netloc or "").lower() path = (parsed.path or "").strip("/") # HuggingFace Spaces if ("huggingface.co" in netloc or "hf.co" in netloc) and path.startswith("spaces/"): parts = path.split("/") if len(parts) >= 3: return "hf_space", {"username": parts[1], "project": parts[2]} # HuggingFace Model if ("huggingface.co" in netloc or "hf.co" in netloc) and not path.startswith(("spaces/", "datasets/")): parts = path.split("/") if len(parts) >= 2: return "hf_model", {"repo_id": f"{parts[0]}/{parts[1]}"} # GitHub Repository if "github.com" in netloc: parts = path.split("/") if len(parts) >= 2: return "github", {"owner": parts[0], "repo": parts[1]} except Exception: pass return "unknown", None def _is_transformers_js_space(self, username: str, project_name: str) -> bool: """Check if space is a transformers.js app""" try: files = list_repo_files( repo_id=f"{username}/{project_name}", repo_type="space", token=self.hf_token ) has_html = any('index.html' in f for f in files) has_js = any('index.js' in f for f in files) has_css = any('style.css' in f for f in files) return has_html and has_js and has_css except: return False def _fetch_transformers_js_files(self, username: str, project_name: str) -> Tuple[str, Dict]: """Fetch transformers.js files and combine them""" files = {} file_names = ['index.html', 'index.js', 'style.css'] for file_name in file_names: try: content_path = self.api.hf_hub_download( repo_id=f"{username}/{project_name}", filename=file_name, repo_type="space" ) with open(content_path, 'r', encoding='utf-8') as f: files[file_name] = f.read() except: files[file_name] = "" # Combine files combined = f"""=== index.html ==={files.get('index.html', '')}
=== index.js ==={files.get('index.js', '')}
=== style.css ==={files.get('style.css', '')}""" return combined, files def _fetch_all_space_files(self, username: str, project_name: str, sdk: str) -> Optional[Dict[str, str]]: """Fetch all relevant files from a space""" try: space_id = f"{username}/{project_name}" files = list_repo_files(repo_id=space_id, repo_type="space", token=self.hf_token) # Define file extensions to include include_extensions = { '.py', '.js', '.html', '.css', '.json', '.txt', '.yml', '.yaml', '.toml', '.cfg', '.ini', '.sh', '.md' } # Filter files relevant_files = [ f for f in files if any(f.endswith(ext) for ext in include_extensions) and not f.startswith('.') and not f.startswith('__pycache__') ] # Limit number of files if len(relevant_files) > 50: relevant_files = relevant_files[:50] # Fetch file contents file_contents = {} for file in relevant_files: try: file_path = self.api.hf_hub_download( repo_id=space_id, filename=file, repo_type="space" ) with open(file_path, 'r', encoding='utf-8') as f: file_contents[file] = f.read() except: continue return file_contents if file_contents else None except: return None def _format_multi_file_content(self, files: Dict[str, str], username: str, project_name: str, sdk: str) -> str: """Format multi-file content""" header = f"""IMPORTED PROJECT FROM HUGGING FACE SPACE==============================================
Space: {username}/{project_name}SDK: {sdk}Files: {len(files)}
""" file_sections = [] for filename, content in files.items(): file_sections.append(f"=== {filename} ===\n{content}") return header + "\n\n".join(file_sections) def _fetch_main_file(self, username: str, project_name: str, sdk: str) -> Tuple[Optional[str], Optional[str]]: """Fetch main file from space""" file_patterns = self._get_file_patterns_for_sdk(sdk) for file_pattern in file_patterns: try: content_path = self.api.hf_hub_download( repo_id=f"{username}/{project_name}", filename=file_pattern, repo_type="space" ) with open(content_path, 'r', encoding='utf-8') as f: return file_pattern, f.read() except: continue return None, None def _get_file_patterns_for_sdk(self, sdk: str) -> List[str]: """Get file patterns to try based on SDK""" patterns = { "static": ["index.html"], "gradio": ["app.py", "main.py", "gradio_app.py"], "streamlit": [ "streamlit_app.py", "src/streamlit_app.py", "app.py", "src/app.py", "main.py", "src/main.py", "Home.py", "src/Home.py" ] } return patterns.get(sdk, ["app.py", "main.py", "index.html"]) def _detect_language_from_sdk(self, sdk: str) -> str: """Detect language/framework from SDK""" sdk_map = { "gradio": "gradio", "streamlit": "streamlit", "static": "html", "docker": "docker" } return sdk_map.get(sdk, "python") def _generate_inference_code(self, model_id: str, pipeline_tag: Optional[str]) -> Optional[str]: """Generate inference provider code based on pipeline tag""" if not pipeline_tag: return None templates = { "text-generation": f'''import osfrom huggingface_hub import InferenceClient
client = InferenceClient(api_key=os.environ["HF_TOKEN"])
completion = client.chat.completions.create( model="{model_id}", messages=[ {{"role": "user", "content": "What is the capital of France?"}} ],)
print(completion.choices[0].message)''', "text-to-image": f'''import osfrom huggingface_hub import InferenceClient
client = InferenceClient(api_key=os.environ["HF_TOKEN"])
# output is a PIL.Image objectimage = client.text_to_image( "Astronaut riding a horse", model="{model_id}",)
# Save the imageimage.save("output.png")''', "automatic-speech-recognition": f'''import osfrom huggingface_hub import InferenceClient
client = InferenceClient(api_key=os.environ["HF_TOKEN"])
with open("audio.mp3", "rb") as f: audio_data = f.read()
result = client.automatic_speech_recognition( audio_data, model="{model_id}",)
print(result)''', "text-to-speech": f'''import osfrom huggingface_hub import InferenceClient
client = InferenceClient(api_key=os.environ["HF_TOKEN"])
audio = client.text_to_speech( "Hello world", model="{model_id}",)
# Save the audiowith open("output.mp3", "wb") as f: f.write(audio)''', } return templates.get(pipeline_tag) def _fetch_hf_model_readme(self, repo_id: str) -> Optional[str]: """Fetch README from HuggingFace model""" try: local_path = self.api.hf_hub_download( repo_id=repo_id, filename="README.md", repo_type="model" ) with open(local_path, "r", encoding="utf-8") as f: return f.read() except: return None def _fetch_github_readme(self, owner: str, repo: str) -> Optional[str]: """Fetch README from GitHub repository""" urls = [ f"https://raw.githubusercontent.com/{owner}/{repo}/HEAD/README.md", f"https://raw.githubusercontent.com/{owner}/{repo}/main/README.md", f"https://raw.githubusercontent.com/{owner}/{repo}/master/README.md", ] for url in urls: try: resp = requests.get(url, timeout=10) if resp.status_code == 200 and resp.text: return resp.text except: continue return None def _extract_code_from_markdown(self, markdown: str) -> Tuple[Optional[str], Optional[str]]: """Extract relevant code from markdown""" if not markdown: return None, None # Find all code blocks code_blocks = [] for match in re.finditer(r"```([\w+-]+)?\s*\n([\s\S]*?)```", markdown, re.IGNORECASE): lang = (match.group(1) or "").lower() code = match.group(2) or "" code_blocks.append((lang, code.strip())) # Score blocks based on relevance def score_block(code: str) -> int: score = 0 keywords = [ "from transformers", "import transformers", "pipeline(", "AutoModel", "AutoTokenizer", "text-generation", "from diffusers", "import diffusers", "DiffusionPipeline", "StableDiffusion", "from gradio", "import gradio" ] for kw in keywords: if kw in code: score += 1 score += min(len(code) // 200, 5) return score # Filter and sort relevant = [ cb for cb in code_blocks if any(kw in cb[1] for kw in ["transformers", "diffusers", "pipeline(", "gradio", "import"]) ] if relevant: sorted_blocks = sorted(relevant, key=lambda x: score_block(x[1]), reverse=True) return sorted_blocks[0][0] or "python", sorted_blocks[0][1] return None, None
# ==================== CLI Interface ====================
def main(): """CLI interface for project importer""" import argparse parser = argparse.ArgumentParser( description="Import projects from HuggingFace Spaces, Models, or GitHub repos" ) parser.add_argument("url", help="URL to import from") parser.add_argument("-o", "--output", help="Output file to save code", default=None) parser.add_argument("--prefer-local", action="store_true", help="Prefer local inference code over serverless (for models)") parser.add_argument("--token", help="HuggingFace token", default=None) args = parser.parse_args() # Initialize importer importer = ProjectImporter(hf_token=args.token) # Import project print(f"Importing from: {args.url}") print("-" * 60) result = importer.import_from_url(args.url) # Print results print(f"Status: {result['status']}") print(f"Message: {result['message']}") print(f"Language: {result['language']}") print(f"URL: {result['url']}") if result.get('metadata'): print(f"Metadata: {result['metadata']}") print("-" * 60) if result['code']: if args.output: with open(args.output, 'w', encoding='utf-8') as f: f.write(result['code']) print(f"Code saved to: {args.output}") else: print("Code:") print("=" * 60) print(result['code']) print("=" * 60) else: print("No code to display")
if __name__ == "__main__": main()
backend_api.py+111
examples/import_project_example.pyAdded+166
frontend/src/app/page.tsx+17
frontend/src/components/ControlPanel.tsx+107-1
frontend/src/lib/api.ts+22
project_importer.pyAdded+682