Spaces:
Running
Running
| import gradio as gr | |
| from i18n import get_text | |
| def create_model_selector(model_specs, default_model_constant, lang_state, initial_lang): | |
| """ | |
| Creates a reusable Gradio model selector component that is language-aware. | |
| Args: | |
| model_specs (dict): A dictionary containing the specifications for each model. | |
| default_model_constant (str): The key for the default model in the model_specs dictionary. | |
| lang_state (gr.State): The Gradio state object holding the current language. | |
| initial_lang (str): The initial language to set up the component. | |
| Returns: | |
| tuple: A tuple containing the model dropdown and the model description markdown components. | |
| """ | |
| display_names = [d["display_name"] for d in model_specs.values()] | |
| default_display_name = model_specs[default_model_constant]["display_name"] | |
| model_dropdown = gr.Dropdown( | |
| choices=display_names, | |
| label=get_text("model_selector_label", initial_lang), | |
| value=default_display_name, | |
| interactive=True | |
| ) | |
| def get_model_description(model_display_name, lang): | |
| """Fetches the description for a given model in the specified language.""" | |
| for model_spec in model_specs.values(): | |
| if model_spec["display_name"] == model_display_name: | |
| # Safely access the description dictionary | |
| description_dict = model_spec.get("description", {}) | |
| return description_dict.get(lang, "Description not available.") | |
| return "Model not found." | |
| model_description_markdown = gr.Markdown( | |
| get_model_description(default_display_name, initial_lang), | |
| container=True | |
| ) | |
| # Handler to update the description based on dropdown and language state | |
| def update_description(model_name, lang): | |
| return get_model_description(model_name, lang) | |
| # Event listener for when the model selection changes | |
| model_dropdown.change( | |
| fn=update_description, | |
| inputs=[model_dropdown, lang_state], | |
| outputs=[model_description_markdown], | |
| show_progress="hidden" | |
| ) | |
| # Event listener for when the language changes | |
| lang_state.change( | |
| fn=update_description, | |
| inputs=[model_dropdown, lang_state], | |
| outputs=[model_description_markdown], | |
| show_progress="hidden" | |
| ) | |
| # Also need to update the label on language change | |
| lang_state.change( | |
| fn=lambda lang: gr.update(label=get_text("model_selector_label", lang)), | |
| inputs=[lang_state], | |
| outputs=[model_dropdown], | |
| show_progress="hidden" | |
| ) | |
| return model_dropdown, model_description_markdown |