add trending models and spaces
Browse filesFiles changed (2)
- anycoder_app/deploy.py+228
- anycoder_app/ui.py+154-1
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 directly response = 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 only for item in recently_trending: if count >= limit: break try: # Check if this is a model (not a space or dataset) repo_type = item.get("repoType") if repo_type != "model": continue # Extract model data repo_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 found task = pipeline_tag or "general" # Clean up task name for display task_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 += 1 except Exception as model_error: print(f"Error processing trending item: {model_error}") continue if not trending_list: print("No models found in trending list, using fallback") # Fallback: use list_models with downloads sort try: api = HfApi() models = api.list_models(sort="downloads", limit=limit) for model in models: model_id = model.id task = 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_list except Exception as e: print(f"Error fetching trending models: {e}") # Fallback to most downloaded models try: api = HfApi() models = api.list_models(sort="downloads", limit=limit) trending_list = [] for model in models: model_id = model.id task = 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_list except 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 spaces response = 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 items for item in recently_trending: if count >= limit: break try: # Check if this is a space repo_type = item.get("repoType") if repo_type != "space": continue # Extract space data repo_data = item.get("repoData", {}) space_id = repo_data.get("id") if not space_id: continue # Get title and category title = repo_data.get("title") or space_id category = repo_data.get("ai_category") or repo_data.get("shortDescription", "Space") # Create display name: "title (category)" # Truncate long titles if len(title) > 40: title = title[:37] + "..." display_name = f"{title} ({category})" trending_list.append((display_name, space_id)) count += 1 except Exception as space_error: print(f"Error processing trending space: {space_error}") continue if not trending_list: return [("No spaces available", "")] return trending_list except 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 URL space_url = f"https://huggingface.co/spaces/{space_id}" # Use existing load_project_from_url function status, code = load_project_from_url(space_url) # Determine language based on code content code_lang = "html" # default language = "html" # for language dropdown # Check imports to determine framework for Python code if 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 spaces return status, code, language, space_url
def 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 URL model_url = f"https://huggingface.co/{model_id}" # Use existing import_repo_to_app function status, code, _ = import_repo_to_app(model_url) # Determine language - default to python for model imports language = "gradio" # Default framework for model demos return status, code, language, model_url
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.
25 unmodified lines26272829293031323383 unmodified lines1171181191201211221231241251261271281291301311321331341351361371381391401411421625 unmodified lines176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190325 unmodified lines generation_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 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 lines load_project_btn = gr.Button("๐ฅ Import Project", variant="secondary", size="sm", visible=True) load_project_status = gr.Markdown(visible=False) # Trending HuggingFace Models section trending_models_dropdown = gr.Dropdown( label="๐ฅ Trending HuggingFace Models", choices=[], # Will be populated on load value=None, interactive=True, visible=True ) trending_models_status = gr.Markdown(visible=False) # Trending HuggingFace Spaces section trending_spaces_dropdown = gr.Dropdown( label="๐ Trending HuggingFace Spaces", choices=[], # Will be populated on load value=None, interactive=True, visible=True ) trending_spaces_status = gr.Markdown(visible=False) # Chat history display in sidebar chat_history = gr.Chatbot( label="Conversation History",1625 unmodified lines outputs=[input, btn], queue=False ) # Load trending models when app starts def 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 IDs choices = [(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 starts def 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 IDs choices = [(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 selection def 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), # status gr.update(), # code_output gr.update(), # language_dropdown hist, # history history_to_chatbot_messages(hist), # history_output history_to_chatbot_messages(hist), # chat_history gr.update(value=None) # reset dropdown ] # Import the model status, code, language, model_url = import_model_from_hf(model_id) # Add to history loaded_history = hist + [[f"Imported model: {model_id}", code]] # Determine code language for display code_lang = "python" return [ gr.update(value=status, visible=True), # status gr.update(value=code, language=code_lang), # code_output gr.update(value=language), # language_dropdown loaded_history, # history history_to_chatbot_messages(loaded_history), # history_output history_to_chatbot_messages(loaded_history), # chat_history gr.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 selection def 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), # status gr.update(), # code_output gr.update(), # language_dropdown hist, # history history_to_chatbot_messages(hist), # history_output history_to_chatbot_messages(hist), # chat_history gr.update(visible=True), # deploy_btn gr.update(value=None) # reset dropdown ] # Import the space status, code, language, space_url = import_space_from_hf(space_id) # Add to history loaded_history = hist + [[f"Imported space: {space_id}", code]] # Determine code language for display based on framework if 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), # status gr.update(value=code, language=code_lang), # code_output gr.update(value=language), # language_dropdown loaded_history, # history history_to_chatbot_messages(loaded_history), # history_output history_to_chatbot_messages(loaded_history), # chat_history gr.update(value="Publish", visible=True), # deploy_btn gr.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