2506minecraft commited on
Commit
010c9cb
·
verified ·
1 Parent(s): 5d0acc7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -47
app.py CHANGED
@@ -6,9 +6,14 @@ from transformers import pipeline, AutoTokenizer, VitsModel
6
  import torchaudio
7
  import librosa
8
  import soundfile as sf
 
 
9
 
10
  # تهيئة النظام
11
- logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
 
 
 
12
  logger = logging.getLogger(__name__)
13
 
14
  # تهيئة النماذج
@@ -20,61 +25,81 @@ asr_pipeline = pipeline(
20
  tts_tokenizer = AutoTokenizer.from_pretrained("facebook/mms-tts-ara")
21
  tts_model = VitsModel.from_pretrained("facebook/mms-tts-ara")
22
 
23
- # معالجة الصوت الوارد
24
- async def process_voice(update: Update, context):
25
  try:
26
- # تحميل الملف الصوتي
27
- voice_file = await update.message.voice.get_file()
28
- await voice_file.download_to_drive("user_voice.ogg")
29
-
30
- # تحويل الصوت إلى نص
31
- text = await speech_to_text("user_voice.ogg")
32
-
33
- # توليد الرد
34
- response = await generate_response(text)
35
-
36
- # تحويل النص إلى صوت
37
- await text_to_speech(response)
38
-
39
- # إرسال الرد
40
- await update.message.reply_voice("bot_response.wav")
41
-
42
  except Exception as e:
43
- logger.error(f"Error: {str(e)}")
44
- await update.message.reply_text("عذراً، حدث خطأ ما. يرجى المحاولة لاحقاً.")
45
 
46
- # تحويل الصوت إلى نص
47
  async def speech_to_text(audio_path):
48
- # تحويل الصيغة من ogg إلى wav
49
- audio, sr = librosa.load(audio_path, sr=16000)
50
- sf.write("temp.wav", audio, sr)
51
-
52
- # التعرف على الكلام
53
- result = asr_pipeline("temp.wav")
54
- return result["text"]
 
55
 
56
- # توليد الردود
57
  async def generate_response(text):
58
- chatbot = pipeline("text-generation", model="aubmindlab/aragpt2-base")
59
- response = chatbot(
60
- text,
61
- max_length=100,
62
- num_return_sequences=1,
63
- pad_token_id=50256
64
- )
65
- return response[0]['generated_text']
 
 
 
 
 
 
 
66
 
67
- # تحويل النص إلى صوت
68
  async def text_to_speech(text):
69
- inputs = tts_tokenizer(text, return_tensors="pt")
70
-
71
- with torch.no_grad():
72
- output = tts_model(**inputs)
73
-
74
- waveform = output.waveform[0].numpy()
75
- torchaudio.save("bot_response.wav", torch.Tensor(waveform), tts_model.config.sampling_rate)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
- # تهيئة التطبيق
78
  if __name__ == "__main__":
79
  TOKEN = os.getenv("TELEGRAM_TOKEN")
80
  application = Application.builder().token(TOKEN).build()
 
6
  import torchaudio
7
  import librosa
8
  import soundfile as sf
9
+ from pydub import AudioSegment
10
+ import numpy as np
11
 
12
  # تهيئة النظام
13
+ logging.basicConfig(
14
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
15
+ level=logging.INFO
16
+ )
17
  logger = logging.getLogger(__name__)
18
 
19
  # تهيئة النماذج
 
25
  tts_tokenizer = AutoTokenizer.from_pretrained("facebook/mms-tts-ara")
26
  tts_model = VitsModel.from_pretrained("facebook/mms-tts-ara")
27
 
28
+ def enhance_audio(input_path, output_path):
29
+ """تحسين جودة الصوت باستخدام تأثيرات متقدمة"""
30
  try:
31
+ audio = AudioSegment.from_wav(input_path)
32
+ audio = audio.low_pass_filter(3000)
33
+ audio = audio.high_pass_filter(100)
34
+ audio = audio.normalize()
35
+ audio = audio.fade_in(150).fade_out(150)
36
+ audio.export(output_path, format="wav")
37
+ return True
 
 
 
 
 
 
 
 
 
38
  except Exception as e:
39
+ logger.error(f"فشل تحسين الصوت: {str(e)}")
40
+ return False
41
 
 
42
  async def speech_to_text(audio_path):
43
+ try:
44
+ audio, sr = librosa.load(audio_path, sr=16000)
45
+ sf.write("temp.wav", audio, sr)
46
+ result = asr_pipeline("temp.wav")
47
+ return result["text"]
48
+ except Exception as e:
49
+ logger.error(f"فشل التعرف على الصوت: {str(e)}")
50
+ return ""
51
 
 
52
  async def generate_response(text):
53
+ try:
54
+ chatbot = pipeline(
55
+ "text-generation",
56
+ model="aubmindlab/aragpt2-base"
57
+ )
58
+ response = chatbot(
59
+ text,
60
+ max_length=100,
61
+ num_return_sequences=1,
62
+ pad_token_id=50256
63
+ )
64
+ return response[0]['generated_text']
65
+ except Exception as e:
66
+ logger.error(f"فشل توليد الرد: {str(e)}")
67
+ return "عذرًا، لم أفهم ما تقصد."
68
 
 
69
  async def text_to_speech(text):
70
+ try:
71
+ inputs = tts_tokenizer(text, return_tensors="pt")
72
+ with torch.no_grad():
73
+ output = tts_model(**inputs)
74
+ waveform = output.waveform[0].numpy()
75
+ torchaudio.save("bot_response.wav", torch.Tensor(waveform), tts_model.config.sampling_rate)
76
+ except Exception as e:
77
+ logger.error(f"فشل تحويل النص إلى صوت: {str(e)}")
78
+
79
+ async def process_voice(update: Update, context):
80
+ try:
81
+ user = update.message.from_user
82
+ logger.info(f"رسالة صوتية من {user.first_name}")
83
+
84
+ # تحميل الملف الصوتي
85
+ voice_file = await update.message.voice.get_file()
86
+ await voice_file.download_to_drive("user_voice.ogg")
87
+
88
+ # معالجة الصوت
89
+ user_text = await speech_to_text("user_voice.ogg")
90
+ bot_response = await generate_response(user_text)
91
+ await text_to_speech(bot_response)
92
+
93
+ # تحسين الجودة وإرسال الرد
94
+ if enhance_audio("bot_response.wav", "bot_response_enhanced.wav"):
95
+ await update.message.reply_voice("bot_response_enhanced.wav")
96
+ else:
97
+ await update.message.reply_voice("bot_response.wav")
98
+
99
+ except Exception as e:
100
+ logger.error(f"خطأ رئيسي: {str(e)}")
101
+ await update.message.reply_text("⚠️ حدث خطأ غير متوقع، الرجاء المحاولة لاحقًا.")
102
 
 
103
  if __name__ == "__main__":
104
  TOKEN = os.getenv("TELEGRAM_TOKEN")
105
  application = Application.builder().token(TOKEN).build()