|
|
|
import gradio as gr |
|
from transformers import pipeline |
|
import traceback |
|
|
|
|
|
|
|
MODELS = { |
|
"English": "distilbert-base-uncased-finetuned-sst-2-english", |
|
"Persian (Farsi)": "m3hrdadfi/albert-fa-base-v2-sentiment-binary", |
|
} |
|
|
|
|
|
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] |
|
|
|
|
|
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: |
|
|
|
|
|
error_details = traceback.format_exc() |
|
print(error_details) |
|
return f"An error occurred:\n\n{error_details}" |
|
|
|
|
|
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) |
|
|
|
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 |
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
print("Launching Gradio interface...") |
|
iface.launch() |