canksdi commited on
Commit
afeb9cb
·
verified ·
1 Parent(s): 7d77c1d

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -42
app.py CHANGED
@@ -595,79 +595,167 @@ def process_input(text, personality_choice=None):
595
  return error_msg, None
596
 
597
  # Duygu analizi yap
598
- sentiment_result = sentiment_model(text)[0]
599
- label = sentiment_result['label']
600
- score = sentiment_result['score']
601
-
602
- print(f"Duygu analizi sonucu: {label} ({score:.2f})")
 
 
 
 
 
 
603
 
604
  # Eğer kullanıcı kişilik seçimi yaptıysa onu kullan, yoksa otomatik belirle
605
- emotion, emoji_count = detect_emotion_from_text(text, label, score)
606
- if personality_choice and personality_choice in PERSONALITY_PROFILES:
607
- personality = PERSONALITY_PROFILES[personality_choice]
608
- VOICE = personality["voice"] # Kişiliğe uygun sesi seç
609
- else:
610
- personality = get_personality_profile(text, emotion)
611
- VOICE = personality["voice"]
612
-
613
- print(f"Kullanılacak kişilik: {personality['name']}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
614
 
615
  # Geliştirilmiş promptlar oluştur
616
- prompt = create_better_prompts(text, label, score)
 
 
 
 
 
 
 
617
 
618
  # Türkçe metin üret - kalite kontrolü ile
619
- print("Metin üretiliyor...")
620
- response = generate_turkish_text(prompt, max_length=350)
 
 
 
 
 
 
 
621
 
622
  # Eğer yanıt üretilemediyse veya çok kısaysa
623
  if not response or len(response) < 10:
 
624
  # Daha basit bir prompt ile tekrar dene
625
- simple_prompt = f"Şu konuda yardımcı ve dost cevap ver: '{text}'"
626
- response = generate_turkish_text(simple_prompt, max_length=200)
 
 
 
 
627
 
628
  if not response or len(response) < 10:
629
- response = "Üzgünüm, şu anda anlamlı bir yanıt üretirken sorun yaşıyorum. Lütfen mesajınızı farklı bir şekilde ifade ederek tekrar deneyin."
630
 
631
  # Son temizlik ve kalite kontrolü
632
- response = clean_response(response)
 
 
 
 
 
 
 
 
 
 
633
 
634
  # Yanıt kalitesi çok düşükse, yedek yanıtlar kullan
635
- if score_response_quality(response) < 0.4:
636
- fallback_responses = [
637
- f"Mesajını aldım. '{text}' konusunda seninle tamamen aynı fikirdeyim. Bunu biraz daha açabilir misin?",
638
- f"'{text}' hakkında ne hissettiğini anlıyorum. Bu konuda daha fazla konuşmak ister misin?",
639
- f"Bu durumu yaşamak gerçekten zor olmalı. Seninle daha fazla konuşmak ve nasıl yardımcı olabileceğimi bulmak isterim.",
640
- f"Düşüncelerini paylaştığın için teşekkür ederim. Bu konuda seni daha iyi anlamak istiyorum. Detaylı anlatır mısın?"
641
- ]
642
- response = random.choice(fallback_responses)
 
 
 
 
 
 
 
643
 
644
  # Uzman önerileri ekle - belirli şartlara göre ve kalite kontrolü ile
645
- if label == "NEGATIVE" and score > 0.7 and random.random() < 0.6: # %60 ihtimalle olumsuz durumlarda öneri ekle
646
- recommendations = get_appropriate_expert_recommendations(text, emotion, score)
647
- if recommendations:
648
- formatted_recs = format_recommendations(recommendations)
649
- if len(response) + len(formatted_recs) <= 600: # Çok uzun olmamasına dikkat et
650
- response += formatted_recs
 
 
 
 
 
651
 
652
  # Emoji ekle - duygu durumuna göre
653
- if random.random() < 0.5: # %50 ihtimalle emoji ekle (fazla emoji kullanımı azaltıldı)
654
- response = add_emojis(response, emotion, emoji_count)
655
-
656
- print(f"Üretilen yanıt: {response[:50]}...")
 
 
 
657
 
658
  # Yüksek kaliteli doğal ses üret - kişiliğe uygun sesle
659
- print("Doğal ses üretiliyor...")
660
- audio_path = create_speech(response)
 
 
 
 
 
 
661
 
662
  process_time = time.time() - start_time
663
  print(f"İşlem tamamlandı ({process_time:.2f} saniye)")
664
 
 
 
 
 
665
  return response, audio_path
666
 
667
  except Exception as e:
668
  error_msg = f"İşlem sırasında bir hata oluştu: {str(e)}"
669
  print(error_msg)
670
- return "Üzgünüm, bir sorun oluştu. Lütfen tekrar deneyin.", None
 
 
671
 
672
  # Demo başlığı ve açıklaması
673
  title = "MoodF - Duygusal Destek Asistanı"
 
595
  return error_msg, None
596
 
597
  # Duygu analizi yap
598
+ try:
599
+ sentiment_result = sentiment_model(text)[0]
600
+ label = sentiment_result['label']
601
+ score = sentiment_result['score']
602
+ print(f"Duygu analizi sonucu: {label} ({score:.2f})")
603
+ except Exception as e:
604
+ print(f"Duygu analizi hatası: {str(e)}")
605
+ # Varsayılan değerler kullan
606
+ label = "NEUTRAL"
607
+ score = 0.5
608
+ print("Varsayılan duygu değerleri kullanılıyor")
609
 
610
  # Eğer kullanıcı kişilik seçimi yaptıysa onu kullan, yoksa otomatik belirle
611
+ try:
612
+ emotion, emoji_count = detect_emotion_from_text(text, label, score)
613
+
614
+ if personality_choice:
615
+ # Doğrudan kimlik yerine isim ile eşleşme arama
616
+ if personality_choice in PERSONALITY_PROFILES:
617
+ personality = PERSONALITY_PROFILES[personality_choice]
618
+ else:
619
+ # İsim ile karşılaştırma
620
+ found = False
621
+ for pid, p in PERSONALITY_PROFILES.items():
622
+ if p["name"] == personality_choice:
623
+ personality = p
624
+ personality_choice = pid
625
+ found = True
626
+ break
627
+ if not found:
628
+ # Varsayılan kişilik kullan
629
+ personality = PERSONALITY_PROFILES[DEFAULT_PERSONALITY]
630
+ print(f"Kişilik bulunamadı ({personality_choice}), varsayılan kullanılıyor")
631
+ else:
632
+ personality = get_personality_profile(text, emotion)
633
+
634
+ # Kişilik için ses seç
635
+ VOICE = personality.get("voice", "tr-TR-EmelNeural")
636
+ print(f"Kullanılacak kişilik: {personality.get('name', 'Bilinmeyen')}")
637
+
638
+ except Exception as e:
639
+ print(f"Kişilik belirleme hatası: {str(e)}")
640
+ # Varsayılan kişilik
641
+ personality = PERSONALITY_PROFILES[DEFAULT_PERSONALITY]
642
+ emotion = "destek"
643
+ emoji_count = 0
644
+ VOICE = "tr-TR-EmelNeural"
645
+ print("Varsayılan kişilik kullanılıyor")
646
 
647
  # Geliştirilmiş promptlar oluştur
648
+ try:
649
+ prompt = create_better_prompts(text, label, score)
650
+ print(f"Prompt oluşturuldu: {prompt[:100]}...")
651
+ except Exception as e:
652
+ print(f"Prompt oluşturma hatası: {str(e)}")
653
+ # Basit prompt kullan
654
+ prompt = f"Bu kişinin mesajına sıcak ve destekleyici bir şekilde yanıt ver: '{text}'"
655
+ print("Basit prompt kullanılıyor")
656
 
657
  # Türkçe metin üret - kalite kontrolü ile
658
+ try:
659
+ print("Metin üretiliyor...")
660
+ response = generate_turkish_text(prompt, max_length=350)
661
+ print(f"Metin üretildi: {response[:50]}...")
662
+ except Exception as e:
663
+ print(f"Metin üretme hatası: {str(e)}")
664
+ # Yedek yanıt
665
+ response = f"Mesajını aldım. Seninle konuşmak güzel. Bu konuda daha fazla konuşmak ister misin?"
666
+ print("Yedek yanıt kullanılıyor")
667
 
668
  # Eğer yanıt üretilemediyse veya çok kısaysa
669
  if not response or len(response) < 10:
670
+ print("Yanıt çok kısa, tekrar deneniyor...")
671
  # Daha basit bir prompt ile tekrar dene
672
+ try:
673
+ simple_prompt = f"Şu konuda yardımcı ve dost cevap ver: '{text}'"
674
+ response = generate_turkish_text(simple_prompt, max_length=200)
675
+ except Exception as e:
676
+ print(f"İkinci deneme hatası: {str(e)}")
677
+ response = "Merhaba! Mesajını aldım. Nasıl yardımcı olabilirim?"
678
 
679
  if not response or len(response) < 10:
680
+ response = "Seninle konuşmak güzel. Bu konuda daha fazla konuşmak ister misin?"
681
 
682
  # Son temizlik ve kalite kontrolü
683
+ try:
684
+ response = clean_response(response)
685
+ print(f"Temizlenmiş yanıt: {response[:50]}...")
686
+ except Exception as e:
687
+ print(f"Yanıt temizleme hatası: {str(e)}")
688
+ # Basit temizlik
689
+ response = re.sub(r'\s+', ' ', response).strip()
690
+ if response:
691
+ response = response[0].upper() + response[1:]
692
+ if not response[-1] in ['.', '!', '?']:
693
+ response += '.'
694
 
695
  # Yanıt kalitesi çok düşükse, yedek yanıtlar kullan
696
+ try:
697
+ quality_score = score_response_quality(response)
698
+ print(f"Yanıt kalite skoru: {quality_score:.2f}")
699
+ if quality_score < 0.4:
700
+ fallback_responses = [
701
+ f"Mesajını aldım. Bu konuda düşüncelerini paylaşmak ister misin?",
702
+ f"Bu konuda nasıl hissettiğini anlıyorum. Daha fazla konuşmak ister misin?",
703
+ f"Paylaştığın için teşekkür ederim. Seni dinlemek güzel.",
704
+ f"Düşüncelerini paylaştığın için teşekkürler. Nasıl hissettiğini anlamak istiyorum."
705
+ ]
706
+ response = random.choice(fallback_responses)
707
+ print("Yedek yanıt kullanıldı")
708
+ except Exception as e:
709
+ print(f"Kalite skoru hatası: {str(e)}")
710
+ # Kalite skoru kontrolü atlama
711
 
712
  # Uzman önerileri ekle - belirli şartlara göre ve kalite kontrolü ile
713
+ try:
714
+ if label == "NEGATIVE" and score > 0.7 and random.random() < 0.6: # %60 ihtimalle olumsuz durumlarda öneri ekle
715
+ recommendations = get_appropriate_expert_recommendations(text, emotion, score)
716
+ if recommendations:
717
+ formatted_recs = format_recommendations(recommendations)
718
+ if len(response) + len(formatted_recs) <= 600: # Çok uzun olmamasına dikkat et
719
+ response += formatted_recs
720
+ print("Uzman önerileri eklendi")
721
+ except Exception as e:
722
+ print(f"Uzman önerileri hatası: {str(e)}")
723
+ # Önerileri ekleme
724
 
725
  # Emoji ekle - duygu durumuna göre
726
+ try:
727
+ if random.random() < 0.5: # %50 ihtimalle emoji ekle (fazla emoji kullanımı azaltıldı)
728
+ response = add_emojis(response, emotion, emoji_count)
729
+ print("Emoji eklendi")
730
+ except Exception as e:
731
+ print(f"Emoji ekleme hatası: {str(e)}")
732
+ # Emoji eklememe
733
 
734
  # Yüksek kaliteli doğal ses üret - kişiliğe uygun sesle
735
+ try:
736
+ print("Doğal ses üretiliyor...")
737
+ audio_path = create_speech(response)
738
+ print(f"Ses dosyası: {audio_path}")
739
+ except Exception as e:
740
+ print(f"Ses üretme hatası: {str(e)}")
741
+ audio_path = None
742
+ # Ses dosyası oluşturulamadı
743
 
744
  process_time = time.time() - start_time
745
  print(f"İşlem tamamlandı ({process_time:.2f} saniye)")
746
 
747
+ # Her durumda bir yanıt döndürdüğünden emin ol
748
+ if not response or len(response.strip()) < 5:
749
+ response = "Merhaba! Seninle sohbet etmek güzel. Nasıl yardımcı olabilirim?"
750
+
751
  return response, audio_path
752
 
753
  except Exception as e:
754
  error_msg = f"İşlem sırasında bir hata oluştu: {str(e)}"
755
  print(error_msg)
756
+ import traceback
757
+ print(f"Hata detayı: {traceback.format_exc()}")
758
+ return "Merhaba! Şu anda teknik bir sorun yaşıyoruz ama seninle konuşmak istiyorum. Lütfen farklı bir şey söyle veya biraz sonra tekrar dene.", None
759
 
760
  # Demo başlığı ve açıklaması
761
  title = "MoodF - Duygusal Destek Asistanı"