import gradio as gr from transformers import pipeline # Sentiment analysis model'ini yükle sentiment_pipeline = pipeline( "sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment-latest", top_k=None ) def analyze_sentiment(text): """ Verilen metni analiz eder ve duygu sonucunu döner. Args: text (str): Analiz edilecek metin Returns: dict: Sentiment etiketi ve skorları """ if not text or text.strip() == "": return { "error": "Please provide a text to analyze", "sentiment": "neutral", "score": 0.5 } try: # Model'den tahmin al results = sentiment_pipeline(text)[0] # En yüksek skora sahip sentiment'i bul top_result = max(results, key=lambda x: x['score']) # Label'ı normalize et (positive, negative, neutral) label = top_result['label'].lower() score = top_result['score'] # Label mapping (model'e göre değişebilir) sentiment_map = { 'positive': 'positive', 'pos': 'positive', 'negative': 'negative', 'neg': 'negative', 'neutral': 'neutral', 'neu': 'neutral' } sentiment = sentiment_map.get(label, 'neutral') # Negative için score'u normalize et if sentiment == 'negative': score = 1.0 - score return { "sentiment": sentiment, "score": round(score, 4), "all_scores": results } except Exception as e: return { "error": str(e), "sentiment": "neutral", "score": 0.5 } # Gradio arayüzü oluştur def gradio_interface(text): result = analyze_sentiment(text) if "error" in result: return f"⚠️ Error: {result['error']}\n\nDefault: {result['sentiment']} ({result['score']})" sentiment = result['sentiment'] score = result['score'] # Emoji ekle emoji_map = { 'positive': '😊', 'negative': '😞', 'neutral': '😐' } emoji = emoji_map.get(sentiment, '😐') output = f"{emoji} **Sentiment:** {sentiment.upper()}\n" output += f"📊 **Score:** {score}\n\n" output += "**All Scores:**\n" for item in result['all_scores']: output += f"- {item['label']}: {item['score']:.4f}\n" return output # Gradio UI demo = gr.Interface( fn=gradio_interface, inputs=gr.Textbox( lines=3, placeholder="Enter text to analyze sentiment...", label="Input Text" ), outputs=gr.Markdown(label="Sentiment Analysis Result"), title="🤖 Sentiment Analysis API", description="Real-time sentiment analysis using Hugging Face Transformers. Analyzes text and returns positive, negative, or neutral sentiment with confidence scores.", examples=[ ["This is amazing! I love it!"], ["I'm so sad and disappointed."], ["The weather is okay today."], ["Bu harika bir gün! Çok mutluyum."], ["Berbat bir deneyimdi, hiç beğenmedim."] ], theme=gr.themes.Soft(), api_name="analyze" ) if __name__ == "__main__": demo.launch()