add inference provider code
Browse filesFiles changed (2)
- anycoder_app/deploy.py+396-6
- anycoder_app/ui.py+56-5
2029 unmodified lines2030203120322033203420352036203720383 unmodified lines20422043204420452046204720482049205020512052205320542029 unmodified linesreturn 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)"""3 unmodified lines# 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]:2029 unmodified lines20302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923303 unmodified lines2334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442029 unmodified linesreturn status, code, language, space_urldef _generate_inference_code_template(model_id: str, pipeline_tag: Optional[str], has_inference_providers: bool) -> Optional[str]:"""Generate inference provider code template based on model's pipeline tag.Args:model_id: The HuggingFace model IDpipeline_tag: The model's pipeline tag (e.g., "text-generation", "text-to-image")has_inference_providers: Whether the model has inference providers availableReturns:Generated code snippet or None"""if not has_inference_providers:return None# Map pipeline tags to code templates based on HuggingFace Inference Providers docs# https://huggingface.co/docs/inference-providers# Chat Completion / Text Generation modelsif pipeline_tag in ["text-generation", "conversational"]:return f'''import osfrom huggingface_hub import InferenceClientclient = 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)'''# Vision-Language Models (Image-Text to Text)elif pipeline_tag in ["image-text-to-text", "visual-question-answering"]:return f'''import osfrom huggingface_hub import InferenceClientclient = InferenceClient(api_key=os.environ["HF_TOKEN"],)completion = client.chat.completions.create(model="{model_id}",messages=[{{"role": "user","content": [{{"type": "text","text": "Describe this image in one sentence."}},{{"type": "image_url","image_url": {{"url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"}}}}]}}],)print(completion.choices[0].message)'''# Text to Image modelselif pipeline_tag == "text-to-image":return f'''import osfrom huggingface_hub import InferenceClientclient = 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")'''# Text to Video modelselif pipeline_tag == "text-to-video":return f'''import osfrom huggingface_hub import InferenceClientclient = InferenceClient(api_key=os.environ["HF_TOKEN"],)video = client.text_to_video("A young man walking on the street",model="{model_id}",)# Save the videowith open("output.mp4", "wb") as f:f.write(video)'''# Image to Image modelselif pipeline_tag == "image-to-image":return f'''import osfrom huggingface_hub import InferenceClientfrom PIL import Imageclient = InferenceClient(api_key=os.environ["HF_TOKEN"],)# Load input imageinput_image = Image.open("input.jpg")# output is a PIL.Image objectoutput_image = client.image_to_image(input_image,model="{model_id}",prompt="Make it more vibrant")# Save the outputoutput_image.save("output.png")'''# Text to Speech modelselif pipeline_tag == "text-to-speech":return f'''import osfrom huggingface_hub import InferenceClientclient = 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)'''# Automatic Speech Recognitionelif pipeline_tag == "automatic-speech-recognition":return f'''import osfrom huggingface_hub import InferenceClientclient = 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)'''# Feature Extraction / Embeddingselif pipeline_tag == "feature-extraction":return f'''import osfrom huggingface_hub import InferenceClientclient = InferenceClient(api_key=os.environ["HF_TOKEN"],)embeddings = client.feature_extraction("Hello world",model="{model_id}",)print(embeddings)'''# Default: try chat completion for conversational modelselse:# If it has inference providers but unknown task, try chat completionreturn f'''import osfrom huggingface_hub import InferenceClientclient = InferenceClient(api_key=os.environ["HF_TOKEN"],)completion = client.chat.completions.create(model="{model_id}",messages=[{{"role": "user","content": "Hello, how are you?"}}],)print(completion.choices[0].message)'''def _fetch_inference_provider_code(model_id: str) -> Optional[str]:"""Fetch inference provider information from HuggingFace API and generate code template.Args:model_id: The HuggingFace model ID (e.g., "moonshotai/Kimi-K2-Thinking")Returns:The code snippet if model has inference providers, None otherwise"""try:# Fetch trending models data from HuggingFace APIresponse = requests.get("https://huggingface.co/api/trending", timeout=10)if response.status_code != 200:print(f"Failed to fetch trending models API: HTTP {response.status_code}")return Nonetrending_data = response.json()recently_trending = trending_data.get("recentlyTrending", [])# Find the specific model in trending datamodel_info = Nonefor item in recently_trending:repo_data = item.get("repoData", {})if repo_data.get("id") == model_id:model_info = repo_databreak# If not found in trending, try to get model info directly from APIif not model_info:try:api = HfApi()info = api.model_info(model_id)pipeline_tag = getattr(info, "pipeline_tag", None)# Check if model has inference providers via model info# Note: The direct API might not have availableInferenceProviders# In this case, we'll generate a generic templatehas_inference = pipeline_tag is not Noneif has_inference:return _generate_inference_code_template(model_id, pipeline_tag, True)except Exception as e:print(f"Could not fetch model info for {model_id}: {e}")return Noneelse:# Extract pipeline tag and inference providers infopipeline_tag = model_info.get("pipeline_tag")inference_providers = model_info.get("availableInferenceProviders", [])has_inference_providers = len(inference_providers) > 0# Generate code template based on pipeline tagreturn _generate_inference_code_template(model_id, pipeline_tag, has_inference_providers)return Noneexcept Exception as e:print(f"Error fetching inference provider code: {e}")return None# Global storage for code alternatives (used when both inference and local code are available)_model_code_alternatives = {}def store_model_code_alternatives(model_id: str, inference_code: Optional[str], local_code: Optional[str]):"""Store both code alternatives for a model for later retrieval."""global _model_code_alternatives_model_code_alternatives[model_id] = {'inference': inference_code,'local': local_code}def get_model_code_alternatives(model_id: str) -> Dict[str, Optional[str]]:"""Retrieve stored code alternatives for a model."""global _model_code_alternativesreturn _model_code_alternatives.get(model_id, {'inference': None, 'local': None})def import_model_from_hf(model_id: str, prefer_local: bool = False) -> Tuple[str, str, str, str]:"""Import a HuggingFace model by ID and extract code snippet.Tries to fetch both inference provider code and transformers/diffusers code from README.Args:model_id: The HuggingFace model IDprefer_local: If True and both options available, return local code instead of inference codeReturns: (status, code, language, model_url)"""3 unmodified lines# Build model URLmodel_url = f"https://huggingface.co/{model_id}"# Try to fetch both types of codeinference_code = _fetch_inference_provider_code(model_id)# Also try to extract transformers/diffusers code from READMEreadme_status, readme_code, _ = import_repo_to_app(model_url)has_readme_code = readme_code and ("transformers" in readme_code or "diffusers" in readme_code)# Store both alternatives for later switchingstore_model_code_alternatives(model_id, inference_code, readme_code if has_readme_code else None)# Build status message and code based on what's availableif inference_code and has_readme_code:# Both available - provide choiceif prefer_local:status = f"""✅ **Found multiple code options for `{model_id}`****Currently showing:** Local Transformers/Diffusers Code (Option 2) 💻**Option 1: Inference Provider Code (Serverless)** ⚡- Uses HuggingFace Inference API (serverless, pay-per-use)- No GPU required, instant startup- Requires `HF_TOKEN` environment variable**Option 2: Local Transformers/Diffusers Code (Currently Active)** 💻- Runs locally on your hardware- Requires GPU for optimal performance- Full control over model parameters---To switch to inference provider code, click the button below or ask: "Show me the inference provider code instead""""code = readme_codeelse:status = f"""✅ **Found multiple code options for `{model_id}`****Currently showing:** Inference Provider Code (Option 1) ⚡ *Recommended***Option 1: Inference Provider Code (Serverless - Currently Active)** ⚡- Uses HuggingFace Inference API (serverless, pay-per-use)- No GPU required, instant startup- Requires `HF_TOKEN` environment variable**Option 2: Local Transformers/Diffusers Code** 💻- Runs locally on your hardware- Requires GPU for optimal performance- Full control over model parameters---To switch to local transformers/diffusers code, click the button below or ask: "Show me the local transformers code instead""""code = inference_codelanguage = "gradio"return status, code, language, model_urlelif inference_code:# Only inference provider code availablestatus = f"✅ Imported inference provider code for `{model_id}` (serverless inference)"language = "gradio"return status, inference_code, language, model_urlelif has_readme_code:# Only README code availablestatus = f"✅ Imported transformers/diffusers code from README for `{model_id}` (local inference)"language = "gradio"return status, readme_code, language, model_urlelse:# No code foundstatus = f"⚠️ No inference provider or transformers/diffusers code found for `{model_id}`"return status, "", "python", model_urldef switch_model_code_type(model_id: str, current_code: str) -> Tuple[str, str]:"""Switch between inference provider code and local transformers/diffusers code.Args:model_id: The model IDcurrent_code: The currently displayed codeReturns: (status_message, new_code)"""alternatives = get_model_code_alternatives(model_id)inference_code = alternatives['inference']local_code = alternatives['local']if not inference_code and not local_code:return "⚠️ No alternative code available for this model.", current_code# Determine which code is currently shownis_showing_inference = current_code == inference_codeif is_showing_inference and local_code:# Switch to local codestatus = f"✅ Switched to **Local Transformers/Diffusers Code** for `{model_id}` 💻\n\nThis code runs locally on your hardware."return status, local_codeelif not is_showing_inference and inference_code:# Switch to inference provider codestatus = f"✅ Switched to **Inference Provider Code** for `{model_id}` ⚡\n\nThis code uses serverless HuggingFace Inference API."return status, inference_codeelse:return "⚠️ Alternative code type not available for this model.", current_codedef import_repo_to_app(url: str, framework: str = "Gradio") -> Tuple[str, str, str]:
44 unmodified lines4546474849505161 unmodified lines11311411511611711836 unmodified lines1551561571581591601773 unmodified lines19341935193619371938193919404 unmodified lines19451946194719481949195019515 unmodified lines1957195819591960196119621 unmodified line19641965196619671968196919706 unmodified lines197719781979198019811982198344 unmodified lines_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)from .agent import (agent_generate_with_questions, agent_process_answers_and_generate61 unmodified linesmodels_first_change = gr.State(True)spaces_first_change = gr.State(True)agent_mode_enabled = gr.State(False)agent_conversation_state = gr.State({"stage": "initial", # initial, waiting_for_answers, generating"original_query": "",36 unmodified linesvisible=True)trending_models_status = gr.Markdown(visible=False)# Trending HuggingFace Spaces sectiontrending_spaces_dropdown = gr.Dropdown(1773 unmodified lineshist, # historyhistory_to_chatbot_messages(hist), # history_outputhistory_to_chatbot_messages(hist), # chat_historyFalse # Set first_change to False after first trigger]if not model_id or model_id == "":4 unmodified lineshist, # historyhistory_to_chatbot_messages(hist), # history_outputhistory_to_chatbot_messages(hist), # chat_historyFalse # Keep first_change as False]# Import the model5 unmodified lines# Determine code language for displaycode_lang = "python"return [gr.update(value=status, visible=True), # statusgr.update(value=code, language=code_lang), # code_output1 unmodified lineloaded_history, # historyhistory_to_chatbot_messages(loaded_history), # history_outputhistory_to_chatbot_messages(loaded_history), # chat_historyFalse # Keep first_change as False]trending_models_dropdown.change(6 unmodified lineshistory,history_output,chat_history,models_first_change])44 unmodified lines454647484950515261 unmodified lines11411511611711811912036 unmodified lines1571581591601611621631773 unmodified lines1937193819391940194119421943194419454 unmodified lines1950195119521953195419551956195719585 unmodified lines1964196519661967196819691970197119721 unmodified line1974197519761977197819791980198119826 unmodified lines198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203444 unmodified lines_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,switch_model_code_type)from .agent import (agent_generate_with_questions, agent_process_answers_and_generate61 unmodified linesmodels_first_change = gr.State(True)spaces_first_change = gr.State(True)agent_mode_enabled = gr.State(False)current_trending_model_id = gr.State("") # Track current trending model for code switchingagent_conversation_state = gr.State({"stage": "initial", # initial, waiting_for_answers, generating"original_query": "",36 unmodified linesvisible=True)trending_models_status = gr.Markdown(visible=False)switch_model_code_btn = gr.Button("🔄 Switch Code Type", visible=False, size="sm", variant="secondary")# Trending HuggingFace Spaces sectiontrending_spaces_dropdown = gr.Dropdown(1773 unmodified lineshist, # historyhistory_to_chatbot_messages(hist), # history_outputhistory_to_chatbot_messages(hist), # chat_historyFalse, # Set first_change to False after first triggergr.update(visible=False), # switch_model_code_btn"" # current_trending_model_id]if not model_id or model_id == "":4 unmodified lineshist, # historyhistory_to_chatbot_messages(hist), # history_outputhistory_to_chatbot_messages(hist), # chat_historyFalse, # Keep first_change as Falsegr.update(visible=False), # switch_model_code_btn"" # current_trending_model_id]# Import the model5 unmodified lines# Determine code language for displaycode_lang = "python"# Check if button should be visible (both code types available)show_switch_btn = "Found multiple code options" in statusreturn [gr.update(value=status, visible=True), # statusgr.update(value=code, language=code_lang), # code_output1 unmodified lineloaded_history, # historyhistory_to_chatbot_messages(loaded_history), # history_outputhistory_to_chatbot_messages(loaded_history), # chat_historyFalse, # Keep first_change as Falsegr.update(visible=show_switch_btn), # switch_model_code_btnmodel_id # current_trending_model_id]trending_models_dropdown.change(6 unmodified lineshistory,history_output,chat_history,models_first_change,switch_model_code_btn,current_trending_model_id])# Handle switching between inference provider and local codedef handle_switch_model_code(model_id, current_code, hist):"""Switch between inference provider and local transformers/diffusers code"""if not model_id:return [gr.update(), # statusgr.update(), # code_outputhist, # historyhistory_to_chatbot_messages(hist), # history_outputhistory_to_chatbot_messages(hist) # chat_history]status_msg, new_code = switch_model_code_type(model_id, current_code)# Update history with switch messageswitch_history = hist + [[f"Switched code type for {model_id}", new_code]]return [gr.update(value=status_msg, visible=True), # statusgr.update(value=new_code, language="python"), # code_outputswitch_history, # historyhistory_to_chatbot_messages(switch_history), # history_outputhistory_to_chatbot_messages(switch_history) # chat_history]switch_model_code_btn.click(handle_switch_model_code,inputs=[current_trending_model_id, code_output, history],outputs=[trending_models_status,code_output,history,history_output,chat_history])
anycoder_app/deploy.py+396-6
anycoder_app/ui.py+56-5