# Import the necessary libraries import gradio as gr from transformers import pipeline import traceback # Import the traceback module to get detailed errors # --- Configuration --- # Define the models we want to offer in our application. MODELS = { "English": "distilbert-base-uncased-finetuned-sst-2-english", "Persian (Farsi)": "m3hrdadfi/albert-fa-base-v2-sentiment-binary", } # --- State and Caching --- pipeline_cache = {} def get_pipeline(model_name): """ Loads a sentiment-analysis pipeline for the given model name. """ if model_name not in pipeline_cache: print(f"Loading pipeline for model: {model_name}...") pipeline_cache[model_name] = pipeline("sentiment-analysis", model=model_name) print("Pipeline loaded successfully.") return pipeline_cache[model_name] # --- Core Logic with Error Handling --- def analyze_sentiment(text, model_choice): """ Analyzes the sentiment of a given text using the selected model. Includes a try-except block to catch and display any errors. """ try: if not text: return "Please enter some text to analyze." model_name = MODELS[model_choice] sentiment_pipeline = get_pipeline(model_name) result = sentiment_pipeline(text)[0] label = result['label'] score = result['score'] return f"Sentiment: {label} (Score: {score:.4f})" except Exception as e: # If any error occurs, format it and return it to the UI. # This is our debugging tool! error_details = traceback.format_exc() print(error_details) # Also print to server logs if we can see them return f"An error occurred:\n\n{error_details}" # --- Gradio Interface --- with gr.Blocks() as iface: gr.Markdown("# Multi-Lingual Sentiment Analyzer") gr.Markdown("Select a language, enter some text, and see the sentiment analysis. The first time you select a language, the model will take a moment to load.") with gr.Row(): model_selector = gr.Dropdown( choices=list(MODELS.keys()), value="English", label="Select Language Model" ) output_text = gr.Textbox(label="Result", interactive=False, lines=10) # Made the box bigger for errors input_text = gr.Textbox(lines=5, placeholder="Enter text here...") submit_button = gr.Button("Analyze Sentiment") submit_button.click( fn=analyze_sentiment, inputs=[input_text, model_selector], outputs=output_text ) # Launch the web application if __name__ == "__main__": print("Launching Gradio interface...") iface.launch()