add import github and HF model support
Browse files3436 unmodified lines343734383439344034413442293 unmodified lines373637373738373937403741374237433744374537463747374837493750375137523753147 unmodified lines3901390239033904390539061 unmodified line390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396569 unmodified lines4035403640374038403940404041404240433436 unmodified linesreturn f"β Successfully imported project from {username}/{project_name}", code_content# Gradio Theme Configurations with proper theme objectsdef get_saved_theme():"""Get the saved theme preference from file"""293 unmodified linesapply_theme_btn = gr.Button("Apply Theme", variant="primary", size="sm")theme_status = gr.Markdown("")# Add Load Project sectiongr.Markdown("π₯ Load Existing Project")load_project_url = gr.Textbox(label="Hugging Face Space URL",placeholder="https://huggingface.co/spaces/username/project",lines=1)load_project_btn = gr.Button("Import Project", variant="secondary", size="sm")load_project_status = gr.Markdown(visible=False)gr.Markdown("---")input = gr.Textbox(label="What would you like to build?",placeholder="Describe your application...",147 unmodified lines)with gr.Tab("Preview"):sandbox = gr.HTML(label="Live preview")# History tab hidden per user request# with gr.Tab("History"):# history_output = gr.Chatbot(show_label=False, height=400, type="messages")1 unmodified line# Keep history_output as hidden component to maintain functionalityhistory_output = gr.Chatbot(show_label=False, height=400, type="messages", visible=False)# Load project functiondef handle_load_project(url):if not url.strip():return gr.update(value="Please enter a URL.", visible=True)status, code = load_project_from_url(url)if code:# Extract space info for deploymentis_valid, username, project_name = check_hf_space_url(url)space_info = f"{username}/{project_name}" if is_valid else ""# Success - update the code output and show success message# Also update history to include the loaded projectloaded_history = [[f"Loaded project from {url}", code]]# Determine preview based on content (HTML or Streamlit)if code and (code.strip().startswith('<!DOCTYPE html>') or code.strip().startswith('<html')):preview_html = send_to_sandbox(code)code_lang = "html"elif is_streamlit_code(code):preview_html = send_streamlit_to_stlite(code)code_lang = "python"elif is_gradio_code(code):preview_html = send_gradio_to_lite(code)code_lang = "python"else:preview_html = "<div style='padding:1em;color:#888;text-align:center;'>Preview not available for this file type.</div>"code_lang = "html"return [gr.update(value=status, visible=True),gr.update(value=code, language=code_lang),gr.update(value=preview_html),gr.update(value=""),loaded_history,history_to_chatbot_messages(loaded_history),gr.update(value=space_info, visible=True), # Update space name with loaded projectgr.update(value="Update Existing Space", visible=True) # Change button text]else:# Error - just show error messagereturn [gr.update(value=status, visible=True),gr.update(),gr.update(),gr.update(),[],[],gr.update(value="", visible=False),gr.update(value="π Deploy App", visible=False)]# Event handlersdef update_code_language(language):return gr.update(language=get_gradio_language(language))69 unmodified lines# No imported project found, return no changesreturn [gr.update(), gr.update()]# Load project button eventload_project_btn.click(handle_load_project,inputs=[load_project_url],outputs=[load_project_status, code_output, sandbox, load_project_url, history, history_output, space_name_input, deploy_btn])3436 unmodified lines343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706293 unmodified lines4000400140024003400440054006400740084009401040114012401340144015147 unmodified lines41634164416541664167416841691 unmodified line4171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424469 unmodified lines4314431543164317431843194320432143223436 unmodified linesreturn f"β Successfully imported project from {username}/{project_name}", code_content# -------- Repo/Model Import (GitHub & Hugging Face model) --------def _parse_repo_or_model_url(url: str) -> Tuple[str, Optional[dict]]:"""Parse a URL and detect if it's a GitHub repo, HF Space, or HF Model.Returns a tuple of (kind, meta) where kind in {"github", "hf_space", "hf_model", "unknown"}Meta contains parsed identifiers."""try:parsed = urlparse(url.strip())netloc = (parsed.netloc or "").lower()path = (parsed.path or "").strip("/")# Hugging Face spacesif ("huggingface.co" in netloc or netloc.endswith("hf.co")) and path.startswith("spaces/"):parts = path.split("/")if len(parts) >= 3:return "hf_space", {"username": parts[1], "project": parts[2]}# Hugging Face model repo (default)if ("huggingface.co" in netloc or netloc.endswith("hf.co")) and not path.startswith(("spaces/", "datasets/", "organizations/")):parts = path.split("/")if len(parts) >= 2:repo_id = f"{parts[0]}/{parts[1]}"return "hf_model", {"repo_id": repo_id}# GitHub repoif "github.com" in netloc:parts = path.split("/")if len(parts) >= 2:return "github", {"owner": parts[0], "repo": parts[1]}except Exception:passreturn "unknown", Nonedef _fetch_hf_model_readme(repo_id: str) -> Optional[str]:"""Fetch README.md (model card) for a Hugging Face model repo."""try:api = HfApi()# Try direct README.md firsttry:local_path = 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 Exception:# Some repos use README at root without explicit typelocal_path = api.hf_hub_download(repo_id=repo_id, filename="README.md")with open(local_path, "r", encoding="utf-8") as f:return f.read()except Exception:return Nonedef _fetch_github_readme(owner: str, repo: str) -> Optional[str]:"""Fetch README.md from a GitHub repo via raw URLs, trying HEAD/main/master."""bases = [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 bases:try:resp = requests.get(url, timeout=10)if resp.status_code == 200 and resp.text:return resp.textexcept Exception:continuereturn Nonedef _extract_transformers_or_diffusers_snippet(markdown_text: str) -> Tuple[Optional[str], Optional[str]]:"""Extract the most relevant Python code block referencing transformers/diffusers from markdown.Returns (language, code). If not found, returns (None, None)."""if not markdown_text:return None, None# Find fenced code blockscode_blocks = []import re as _refor match in _re.finditer(r"```([\w+-]+)?\s*\n([\s\S]*?)```", markdown_text, _re.IGNORECASE):lang = (match.group(1) or "").lower()code = match.group(2) or ""code_blocks.append((lang, code.strip()))# Filter for transformers/diffusers relevancedef score_block(code: str) -> int:score = 0kws = ["from transformers", "import transformers", "pipeline(","AutoModel", "AutoTokenizer", "text-generation","from diffusers", "import diffusers", "DiffusionPipeline","StableDiffusion", "UNet", "EulerDiscreteScheduler"]for kw in kws:if kw in code:score += 1# Prefer longer, self-contained snippetsscore += min(len(code) // 200, 5)return scorescored = sorted([cb for cb in code_blocks if any(kw in cb[1] for kw in ["transformers", "diffusers", "pipeline(", "StableDiffusion"])],key=lambda x: score_block(x[1]),reverse=True,)if scored:return scored[0][0] or None, scored[0][1]return None, Nonedef _infer_task_from_context(snippet: Optional[str], pipeline_tag: Optional[str]) -> str:"""Infer a task string for transformers pipeline; fall back to provided pipeline_tag or 'text-generation'."""if pipeline_tag:return pipeline_tagif not snippet:return "text-generation"lowered = snippet.lower()task_hints = {"text-generation": ["text-generation", "automodelforcausallm"],"text2text-generation": ["text2text-generation", "t5forconditionalgeneration"],"fill-mask": ["fill-mask", "automodelformaskedlm"],"summarization": ["summarization"],"translation": ["translation"],"text-classification": ["text-classification", "sequenceclassification"],"automatic-speech-recognition": ["speechrecognition", "automatic-speech-recognition", "asr"],"image-classification": ["image-classification"],"zero-shot-image-classification": ["zero-shot-image-classification"],}for task, hints in task_hints.items():if any(h in lowered for h in hints):return task# Inspect explicit pipeline("task")import re as _rem = _re.search(r"pipeline\(\s*['\"]([\w\-]+)['\"]", snippet)if m:return m.group(1)return "text-generation"def _generate_gradio_app_from_transformers(repo_id: str, task: str) -> str:"""Build a minimal Gradio app using transformers.pipeline for a given model and task."""# Map simple UI per task; default to text in/outif task in {"text-generation", "text2text-generation", "summarization", "translation", "fill-mask"}:return ("import gradio as gr\n""from transformers import pipeline\n\n"f"pipe = pipeline(task='{task}', model='{repo_id}')\n\n""def infer(prompt, max_new_tokens=256, temperature=0.7, top_p=0.95):\n"" if '\u2047' in prompt:\n"" # Fill-mask often uses [MASK]; keep generic handling\n"" pass\n"" out = pipe(prompt, max_new_tokens=max_new_tokens, do_sample=True, temperature=temperature, top_p=top_p)\n"" if isinstance(out, list):\n"" if isinstance(out[0], dict):\n"" return next(iter(out[0].values())) if out[0] else str(out)\n"" return str(out[0])\n"" return str(out)\n\n""demo = gr.Interface(\n"" fn=infer,\n"" inputs=[gr.Textbox(label='Input', lines=8), gr.Slider(1, 2048, value=256, label='max_new_tokens'), gr.Slider(0.0, 1.5, value=0.7, step=0.01, label='temperature'), gr.Slider(0.0, 1.0, value=0.95, step=0.01, label='top_p')],\n"" outputs=gr.Textbox(label='Output', lines=8),\n"" title='Transformers Demo'\n"")\n\n""if __name__ == '__main__':\n"" demo.launch()\n")elif task in {"text-classification"}:return ("import gradio as gr\n""from transformers import pipeline\n\n"f"pipe = pipeline(task='{task}', model='{repo_id}')\n\n""def infer(text):\n"" out = pipe(text)\n"" # Expect list of dicts with label/score\n"" return {o['label']: float(o['score']) for o in out}\n\n""demo = gr.Interface(fn=infer, inputs=gr.Textbox(lines=6), outputs=gr.Label(), title='Text Classification')\n\n""if __name__ == '__main__':\n"" demo.launch()\n")else:# Fallback generic text pipeline (pipeline infers task from model config)return ("import gradio as gr\n""from transformers import pipeline\n\n"f"pipe = pipeline(model='{repo_id}')\n\n""def infer(prompt):\n"" out = pipe(prompt)\n"" if isinstance(out, list):\n"" if isinstance(out[0], dict):\n"" return next(iter(out[0].values())) if out[0] else str(out)\n"" return str(out[0])\n"" return str(out)\n\n""demo = gr.Interface(fn=infer, inputs=gr.Textbox(lines=8), outputs=gr.Textbox(lines=8), title='Transformers Demo')\n\n""if __name__ == '__main__':\n"" demo.launch()\n")def _generate_gradio_app_from_diffusers(repo_id: str) -> str:"""Build a minimal Gradio app for text-to-image using diffusers."""return ("import gradio as gr\n""import torch\n""from diffusers import DiffusionPipeline\n\n"f"pipe = DiffusionPipeline.from_pretrained('{repo_id}')\n""device = 'cuda' if torch.cuda.is_available() else 'cpu'\n""pipe = pipe.to(device)\n\n""def infer(prompt, guidance_scale=7.0, num_inference_steps=30, seed=0):\n"" generator = None if seed == 0 else torch.Generator(device=device).manual_seed(int(seed))\n"" image = pipe(prompt, guidance_scale=float(guidance_scale), num_inference_steps=int(num_inference_steps), generator=generator).images[0]\n"" return image\n\n""demo = gr.Interface(\n"" fn=infer,\n"" inputs=[gr.Textbox(label='Prompt'), gr.Slider(0.0, 15.0, value=7.0, step=0.1, label='guidance_scale'), gr.Slider(1, 100, value=30, step=1, label='num_inference_steps'), gr.Slider(0, 2**32-1, value=0, step=1, label='seed')],\n"" outputs=gr.Image(type='pil'),\n"" title='Diffusers Text-to-Image'\n"")\n\n""if __name__ == '__main__':\n"" demo.launch()\n")def _generate_streamlit_wrapper(gradio_code: str) -> str:"""Convert a simple Gradio app into a Streamlit wrapper by embedding via components if needed.If code is already Streamlit, return as is. Otherwise, provide a basic Streamlit UI calling the same pipeline."""# For now, simply return a minimal placeholder to keep scope tight; prefer Gradio by default.return ("import streamlit as st\n""st.markdown('This model is best used with a Gradio app in this tool. Switch framework to Gradio for a runnable demo.')\n")def import_repo_to_app(url: str, framework: str = "Gradio") -> Tuple[str, str, str]:"""Import a GitHub or HF model repo and return the raw code snippet from README/model card.Returns (status_markdown, code_snippet, preview_html). Preview left empty; UI will decide."""if not url or not url.strip():return "Please enter a repository URL.", "", ""kind, meta = _parse_repo_or_model_url(url)if kind == "hf_space" and meta:# Spaces already contain runnable apps; keep existing behavior to fetch main file rawstatus, code = load_project_from_url(url)return status, code, ""# Fetch markdownmarkdown = Nonerepo_id = Nonepipeline_tag = Nonelibrary_name = Noneif kind == "hf_model" and meta:repo_id = meta.get("repo_id")# Try model info to get pipeline tag/librarytry:api = HfApi()info = api.model_info(repo_id)pipeline_tag = getattr(info, "pipeline_tag", None)library_name = getattr(info, "library_name", None)except Exception:passmarkdown = _fetch_hf_model_readme(repo_id)elif kind == "github" and meta:markdown = _fetch_github_readme(meta.get("owner"), meta.get("repo"))else:return "Error: Unsupported or invalid URL. Provide a GitHub repo or Hugging Face model URL.", "", ""if not markdown:return "Error: Could not fetch README/model card.", "", ""lang, snippet = _extract_transformers_or_diffusers_snippet(markdown)if not snippet:return "Error: No relevant transformers/diffusers code block found in README/model card.", "", ""status = "β Imported code snippet from README/model card. Use it as a starting point."return status, snippet, ""# Gradio Theme Configurations with proper theme objectsdef get_saved_theme():"""Get the saved theme preference from file"""293 unmodified linesapply_theme_btn = gr.Button("Apply Theme", variant="primary", size="sm")theme_status = gr.Markdown("")# Unified Import sectiongr.Markdown("π₯ Import Project (Space, GitHub, or Model)")load_project_url = gr.Textbox(label="Project URL",placeholder="https://huggingface.co/spaces/user/space OR https://huggingface.co/user/model OR https://github.com/owner/repo",lines=1)load_project_btn = gr.Button("Import Project", variant="secondary", size="sm")load_project_status = gr.Markdown(visible=False)input = gr.Textbox(label="What would you like to build?",placeholder="Describe your application...",147 unmodified lines)with gr.Tab("Preview"):sandbox = gr.HTML(label="Live preview")# Removed Import Logs tab for cleaner UI# History tab hidden per user request# with gr.Tab("History"):# history_output = gr.Chatbot(show_label=False, height=400, type="messages")1 unmodified line# Keep history_output as hidden component to maintain functionalityhistory_output = gr.Chatbot(show_label=False, height=400, type="messages", visible=False)# Unified import handlerdef handle_import_project(url):if not url.strip():return [gr.update(value="Please enter a URL.", visible=True), gr.update(), gr.update(), gr.update(), [], [], gr.update(value="", visible=False), gr.update(value="π Deploy App", visible=False)]kind, meta = _parse_repo_or_model_url(url)if kind == "hf_space":status, code = load_project_from_url(url)# Extract space info for deploymentis_valid, username, project_name = check_hf_space_url(url)space_info = f"{username}/{project_name}" if is_valid else ""loaded_history = [[f"Imported Space from {url}", code]]# Preview not auto-rendered for imported contentcode_lang = "python" if (is_streamlit_code(code) or is_gradio_code(code)) else "html"return [gr.update(value=status, visible=True),gr.update(value=code, language=code_lang),gr.update(value=""),gr.update(value=""),loaded_history,history_to_chatbot_messages(loaded_history),gr.update(value=space_info, visible=True),gr.update(value="Update Existing Space", visible=True)]else:# GitHub or HF model β return raw snippet for LLM starting pointstatus, code, _ = import_repo_to_app(url)loaded_history = [[f"Imported Repo/Model from {url}", code]]code_lang = "python"lower = (code or "").lower()if code.strip().startswith("<!doctype html>") or code.strip().startswith("<html"):code_lang = "html"elif "```json" in lower:code_lang = "json"return [gr.update(value=status, visible=True),gr.update(value=code, language=code_lang),gr.update(value=""),gr.update(value=""),loaded_history,history_to_chatbot_messages(loaded_history),gr.update(value="", visible=False),gr.update(value="π Deploy App", visible=False)]# Import repo/model handlerdef handle_import_repo(url, framework):status, code, preview = import_repo_to_app(url, framework)# Heuristically set editor language based on snippet fencing or contentcode_lang = "python"lowered = (code or "").lower()if code.strip().startswith("<!doctype html>") or code.strip().startswith("<html"):code_lang = "html"elif "import gradio" in lowered or "from gradio" in lowered:code_lang = "python"elif "streamlit as st" in lowered or "import streamlit" in lowered:code_lang = "python"elif "from transformers" in lowered or "import transformers" in lowered:code_lang = "python"elif "from diffusers" in lowered or "import diffusers" in lowered:code_lang = "python"return [gr.update(value=status, visible=True),gr.update(value=code, language=code_lang),gr.update(value=""),gr.update(value=f"URL: {url}\n\n{status}"),]# Event handlersdef update_code_language(language):return gr.update(language=get_gradio_language(language))69 unmodified lines# No imported project found, return no changesreturn [gr.update(), gr.update()]# Unified import eventload_project_btn.click(handle_import_project,inputs=[load_project_url],outputs=[load_project_status, code_output, sandbox, load_project_url, history, history_output, space_name_input, deploy_btn])
app.py+321-42