add trending models and spaces
Browse filesFiles changed (2)
- anycoder_app/deploy.py+228
- anycoder_app/ui.py+154-1
1822 unmodified lines1823182418251826182718281822 unmodified lines" demo.launch()\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.1822 unmodified lines1823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520561822 unmodified lines" demo.launch()\n")def get_trending_models(limit: int = 10) -> List[Tuple[str, str]]:"""Fetch top trending models from HuggingFace Hub.Returns a list of tuples: (display_name, model_id)Display name format: "model_name (task)""""try:# Use the HuggingFace trending API endpoint directlyresponse = requests.get("https://huggingface.co/api/trending")if response.status_code != 200:print(f"Failed to fetch trending models: HTTP {response.status_code}")return [("Unable to load trending models", "")]trending_data = response.json()# The API returns {"recentlyTrending": [...]}recently_trending = trending_data.get("recentlyTrending", [])if not recently_trending:print("No trending items found in API response")return [("No trending models available", "")]trending_list = []count = 0# Process trending items, filter for models onlyfor item in recently_trending:if count >= limit:breaktry:# Check if this is a model (not a space or dataset)repo_type = item.get("repoType")if repo_type != "model":continue# Extract model datarepo_data = item.get("repoData", {})model_id = repo_data.get("id")if not model_id:continue# Get pipeline tag (task type)pipeline_tag = repo_data.get("pipeline_tag")# Default to "general" if no task foundtask = pipeline_tag or "general"# Clean up task name for displaytask_display = task.replace("-", " ").title() if task != "general" else "General"# Create display name: "model_name (Task)"display_name = f"{model_id} ({task_display})"trending_list.append((display_name, model_id))count += 1except Exception as model_error:print(f"Error processing trending item: {model_error}")continueif not trending_list:print("No models found in trending list, using fallback")# Fallback: use list_models with downloads sorttry:api = HfApi()models = api.list_models(sort="downloads", limit=limit)for model in models:model_id = model.idtask = getattr(model, "pipeline_tag", None) or "general"task_display = task.replace("-", " ").title() if task != "general" else "General"display_name = f"{model_id} ({task_display})"trending_list.append((display_name, model_id))except Exception as fallback_error:print(f"Fallback also failed: {fallback_error}")return [("No models available", "")]return trending_listexcept Exception as e:print(f"Error fetching trending models: {e}")# Fallback to most downloaded modelstry:api = HfApi()models = api.list_models(sort="downloads", limit=limit)trending_list = []for model in models:model_id = model.idtask = getattr(model, "pipeline_tag", None) or "general"task_display = task.replace("-", " ").title() if task != "general" else "General"display_name = f"{model_id} ({task_display})"trending_list.append((display_name, model_id))return trending_listexcept Exception:return [("Error loading models", "")]def get_trending_spaces(limit: int = 10) -> List[Tuple[str, str]]:"""Fetch top trending spaces from HuggingFace Hub.Returns a list of tuples: (display_name, space_id)Display name format: "space_name (category)""""try:# Use the HuggingFace trending API endpoint for spacesresponse = requests.get("https://huggingface.co/api/trending?type=space")if response.status_code != 200:print(f"Failed to fetch trending spaces: HTTP {response.status_code}")return [("Unable to load trending spaces", "")]trending_data = response.json()# The API returns {"recentlyTrending": [...]}recently_trending = trending_data.get("recentlyTrending", [])if not recently_trending:print("No trending spaces found in API response")return [("No trending spaces available", "")]trending_list = []count = 0# Process trending itemsfor item in recently_trending:if count >= limit:breaktry:# Check if this is a spacerepo_type = item.get("repoType")if repo_type != "space":continue# Extract space datarepo_data = item.get("repoData", {})space_id = repo_data.get("id")if not space_id:continue# Get title and categorytitle = repo_data.get("title") or space_idcategory = repo_data.get("ai_category") or repo_data.get("shortDescription", "Space")# Create display name: "title (category)"# Truncate long titlesif len(title) > 40:title = title[:37] + "..."display_name = f"{title} ({category})"trending_list.append((display_name, space_id))count += 1except Exception as space_error:print(f"Error processing trending space: {space_error}")continueif not trending_list:return [("No spaces available", "")]return trending_listexcept Exception as e:print(f"Error fetching trending spaces: {e}")return [("Error loading spaces", "")]def import_space_from_hf(space_id: str) -> Tuple[str, str, str, str]:"""Import a HuggingFace space by ID and extract its code.Returns: (status, code, language, space_url)"""if not space_id or space_id == "":return "Please select a space.", "", "html", ""# Build space URLspace_url = f"https://huggingface.co/spaces/{space_id}"# Use existing load_project_from_url functionstatus, code = load_project_from_url(space_url)# Determine language based on code contentcode_lang = "html" # defaultlanguage = "html" # for language dropdown# Check imports to determine framework for Python codeif is_streamlit_code(code):code_lang = "python"language = "streamlit"elif is_gradio_code(code):code_lang = "python"language = "gradio"elif "=== index.html ===" in code and "=== index.js ===" in code:code_lang = "html"language = "transformers.js"elif ("import " in code or "def " in code) and not ("<!DOCTYPE html>" in code or "<html" in code):code_lang = "python"language = "gradio" # Default to Gradio for Python spacesreturn status, code, language, space_urldef import_model_from_hf(model_id: str) -> Tuple[str, str, str, str]:"""Import a HuggingFace model by ID and extract code snippet.Returns: (status, code, language, model_url)"""if not model_id or model_id == "":return "Please select a model.", "", "python", ""# Build model URLmodel_url = f"https://huggingface.co/{model_id}"# Use existing import_repo_to_app functionstatus, code, _ = import_repo_to_app(model_url)# Determine language - default to python for model importslanguage = "gradio" # Default framework for model demosreturn status, code, language, model_urldef 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.
25 unmodified lines2627282930313283 unmodified lines1161171181191201211625 unmodified lines174717481749175025 unmodified linesgeneration_code, deploy_to_spaces, add_anycoder_tag_to_readme,_parse_repo_or_model_url, load_project_from_url, check_hf_space_url,import_repo_to_app, extract_import_statements,generate_requirements_txt_with_llm, prettify_comfyui_json_for_html)# Main application with proper Gradio theming83 unmodified linesload_project_btn = gr.Button("๐ฅ Import Project", variant="secondary", size="sm", visible=True)load_project_status = gr.Markdown(visible=False)# Chat history display in sidebarchat_history = gr.Chatbot(label="Conversation History",1625 unmodified linesoutputs=[input, btn],queue=False)25 unmodified lines262728293031323383 unmodified lines1171181191201211221231241251261271281291301311321331341351361371381391401411421625 unmodified lines176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190325 unmodified linesgeneration_code, deploy_to_spaces, add_anycoder_tag_to_readme,_parse_repo_or_model_url, load_project_from_url, check_hf_space_url,import_repo_to_app, extract_import_statements,generate_requirements_txt_with_llm, prettify_comfyui_json_for_html,get_trending_models, import_model_from_hf, get_trending_spaces, import_space_from_hf)# Main application with proper Gradio theming83 unmodified linesload_project_btn = gr.Button("๐ฅ Import Project", variant="secondary", size="sm", visible=True)load_project_status = gr.Markdown(visible=False)# Trending HuggingFace Models sectiontrending_models_dropdown = gr.Dropdown(label="๐ฅ Trending HuggingFace Models",choices=[], # Will be populated on loadvalue=None,interactive=True,visible=True)trending_models_status = gr.Markdown(visible=False)# Trending HuggingFace Spaces sectiontrending_spaces_dropdown = gr.Dropdown(label="๐ Trending HuggingFace Spaces",choices=[], # Will be populated on loadvalue=None,interactive=True,visible=True)trending_spaces_status = gr.Markdown(visible=False)# Chat history display in sidebarchat_history = gr.Chatbot(label="Conversation History",1625 unmodified linesoutputs=[input, btn],queue=False)# Load trending models when app startsdef load_trending_models():"""Load trending models from HuggingFace Hub"""models = get_trending_models(limit=10)# Create choices list with display names and values as model IDschoices = [(display, model_id) for display, model_id in models]return gr.update(choices=choices)demo.load(load_trending_models,inputs=[],outputs=[trending_models_dropdown],queue=False)# Load trending spaces when app startsdef load_trending_spaces():"""Load trending spaces from HuggingFace Hub"""spaces = get_trending_spaces(limit=10)# Create choices list with display names and values as space IDschoices = [(display, space_id) for display, space_id in spaces]return gr.update(choices=choices)demo.load(load_trending_spaces,inputs=[],outputs=[trending_spaces_dropdown],queue=False)# Handle trending model selectiondef handle_trending_model_selection(model_id, hist):"""Handle when user selects a trending model"""if not model_id or model_id == "":return [gr.update(value="Please select a model.", visible=True), # statusgr.update(), # code_outputgr.update(), # language_dropdownhist, # historyhistory_to_chatbot_messages(hist), # history_outputhistory_to_chatbot_messages(hist), # chat_historygr.update(value=None) # reset dropdown]# Import the modelstatus, code, language, model_url = import_model_from_hf(model_id)# Add to historyloaded_history = hist + [[f"Imported model: {model_id}", code]]# Determine code language for displaycode_lang = "python"return [gr.update(value=status, visible=True), # statusgr.update(value=code, language=code_lang), # code_outputgr.update(value=language), # language_dropdownloaded_history, # historyhistory_to_chatbot_messages(loaded_history), # history_outputhistory_to_chatbot_messages(loaded_history), # chat_historygr.update(value=None) # reset dropdown]trending_models_dropdown.change(handle_trending_model_selection,inputs=[trending_models_dropdown, history],outputs=[trending_models_status,code_output,language_dropdown,history,history_output,chat_history,trending_models_dropdown])# Handle trending space selectiondef handle_trending_space_selection(space_id, hist):"""Handle when user selects a trending space"""if not space_id or space_id == "":return [gr.update(value="Please select a space.", visible=True), # statusgr.update(), # code_outputgr.update(), # language_dropdownhist, # historyhistory_to_chatbot_messages(hist), # history_outputhistory_to_chatbot_messages(hist), # chat_historygr.update(visible=True), # deploy_btngr.update(value=None) # reset dropdown]# Import the spacestatus, code, language, space_url = import_space_from_hf(space_id)# Add to historyloaded_history = hist + [[f"Imported space: {space_id}", code]]# Determine code language for display based on frameworkif language == "gradio" or language == "streamlit":code_lang = "python"elif language == "transformers.js":code_lang = "html"else:code_lang = "html"return [gr.update(value=status, visible=True), # statusgr.update(value=code, language=code_lang), # code_outputgr.update(value=language), # language_dropdownloaded_history, # historyhistory_to_chatbot_messages(loaded_history), # history_outputhistory_to_chatbot_messages(loaded_history), # chat_historygr.update(value="Publish", visible=True), # deploy_btngr.update(value=None) # reset dropdown]trending_spaces_dropdown.change(handle_trending_space_selection,inputs=[trending_spaces_dropdown, history],outputs=[trending_spaces_status,code_output,language_dropdown,history,history_output,chat_history,deploy_btn,trending_spaces_dropdown])
anycoder_app/deploy.py+228
anycoder_app/ui.py+154-1