2506minecraft commited on
Commit
7621729
·
verified ·
1 Parent(s): eb45013

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -0
app.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ from telegram import Update
4
+ from telegram.ext import Application, MessageHandler, filters
5
+ 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
+ # تهيئة النماذج
15
+ asr_pipeline = pipeline(
16
+ "automatic-speech-recognition",
17
+ model="facebook/wav2vec2-large-xlsr-53-arabic"
18
+ )
19
+
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()
81
+ application.add_handler(MessageHandler(filters.VOICE, process_voice))
82
+ application.run_polling()