Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| from transformers import pipeline | |
| from gtts import gTTS | |
| import os | |
| from pathlib import Path | |
| import tempfile | |
| import torch # Added torch import | |
| # Initialize sentiment analysis pipeline | |
| try: | |
| sentiment_pipeline = pipeline( | |
| "sentiment-analysis", | |
| model="nlptown/bert-base-multilingual-uncased-sentiment", | |
| device=0 if torch.cuda.is_available() else -1 | |
| ) | |
| except Exception as e: | |
| raise Exception(f"Failed to load model: {str(e)}") | |
| def analyze_sentiment(text, language): | |
| if not text or not text.strip(): | |
| return "Error: Please enter some text", 0, "No recommendation available", None | |
| try: | |
| result = sentiment_pipeline(text) | |
| sentiment = result[0]['label'] | |
| score = result[0]['score'] | |
| recommendations = { | |
| "Arabic": { | |
| "negative": (("1 star", "2 stars"), "يبدو أنك غير راضٍ، هل يمكننا مساعدتك في العثور على بديل؟"), | |
| "neutral": (("3 stars"), "رأيك محايد، قد ترغب في تجربة خيارات أخرى."), | |
| "positive": (("4 stars", "5 stars"), "ممتاز! يبدو أنك راضٍ، هل ترغب في مشاركة رأيك مع الآخرين؟") | |
| }, | |
| "English": { | |
| "negative": (("1 star", "2 stars"), "You seem unsatisfied, can we help you find an alternative?"), | |
| "neutral": (("3 stars"), "Your opinion is neutral, you may want to explore other options."), | |
| "positive": (("4 stars", "5 stars"), "Great! You seem satisfied, would you like to share your opinion?") | |
| } | |
| } | |
| lang_recs = recommendations[language] | |
| if sentiment in lang_recs["negative"][0]: | |
| recommendation = lang_recs["negative"][1] | |
| elif sentiment in lang_recs["neutral"][0]: | |
| recommendation = lang_recs["neutral"][1] | |
| elif sentiment in lang_recs["positive"][0]: | |
| recommendation = lang_recs["positive"][1] | |
| else: | |
| recommendation = "Unexpected sentiment detected" | |
| with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as tmp: | |
| audio_file = tmp.name | |
| tts = gTTS(recommendation, lang="ar" if language == "Arabic" else "en") | |
| tts.save(audio_file) | |
| return sentiment, round(score, 2), recommendation, audio_file | |
| except Exception as e: | |
| return "Error occurred", 0, f"Error: {str(e)}", None | |
| # Custom CSS with Arabic-friendly font | |
| custom_css = """ | |
| body, .gr-button, .gr-input, .gr-output, .gr-textbox { | |
| font-family: 'Tajawal', 'Arial', sans-serif !important; | |
| } | |
| .gr-button {margin: 5px;} | |
| .output-text {font-size: 16px;} | |
| """ | |
| # Create Gradio interface | |
| with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo: | |
| gr.Markdown("# Sentiment Analysis with Voice Recommendations") | |
| gr.Markdown("Enter text to analyze sentiment and get audio recommendations") | |
| with gr.Row(): | |
| with gr.Column(scale=2): | |
| text_input = gr.Textbox( | |
| label="Your Comment", | |
| placeholder="Type your comment here...", | |
| lines=3 | |
| ) | |
| language_input = gr.Radio( | |
| ["Arabic", "English"], | |
| label="Language", | |
| value="English" | |
| ) | |
| submit_btn = gr.Button("Analyze", variant="primary") | |
| with gr.Column(scale=3): | |
| sentiment_output = gr.Textbox(label="Sentiment") | |
| score_output = gr.Slider(0, 1, label="Confidence Score", interactive=False) | |
| recommendation_output = gr.Textbox(label="Recommendation") | |
| audio_output = gr.Audio(label="Audio Recommendation", type="filepath") | |
| examples = gr.Examples( | |
| examples=[ | |
| ["The product is amazing!", "English"], | |
| ["الخدمة سيئة جداً", "Arabic"], | |
| ["منتج جيد نوعاً ما", "Arabic"], | |
| ["It's okay, nothing special", "English"] | |
| ], | |
| inputs=[text_input, language_input] | |
| ) | |
| submit_btn.click( | |
| fn=analyze_sentiment, | |
| inputs=[text_input, language_input], | |
| outputs=[sentiment_output, score_output, recommendation_output, audio_output] | |
| ) | |
| demo.launch() |