File size: 2,737 Bytes
7621729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import os
import logging
from telegram import Update
from telegram.ext import Application, MessageHandler, filters
from transformers import pipeline, AutoTokenizer, VitsModel
import torchaudio
import librosa
import soundfile as sf

# تهيئة النظام
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)

# تهيئة النماذج
asr_pipeline = pipeline(
    "automatic-speech-recognition",
    model="facebook/wav2vec2-large-xlsr-53-arabic"
)

tts_tokenizer = AutoTokenizer.from_pretrained("facebook/mms-tts-ara")
tts_model = VitsModel.from_pretrained("facebook/mms-tts-ara")

# معالجة الصوت الوارد
async def process_voice(update: Update, context):
    try:
        # تحميل الملف الصوتي
        voice_file = await update.message.voice.get_file()
        await voice_file.download_to_drive("user_voice.ogg")
        
        # تحويل الصوت إلى نص
        text = await speech_to_text("user_voice.ogg")
        
        # توليد الرد
        response = await generate_response(text)
        
        # تحويل النص إلى صوت
        await text_to_speech(response)
        
        # إرسال الرد
        await update.message.reply_voice("bot_response.wav")
        
    except Exception as e:
        logger.error(f"Error: {str(e)}")
        await update.message.reply_text("عذراً، حدث خطأ ما. يرجى المحاولة لاحقاً.")

# تحويل الصوت إلى نص
async def speech_to_text(audio_path):
    # تحويل الصيغة من ogg إلى wav
    audio, sr = librosa.load(audio_path, sr=16000)
    sf.write("temp.wav", audio, sr)
    
    # التعرف على الكلام
    result = asr_pipeline("temp.wav")
    return result["text"]

# توليد الردود
async def generate_response(text):
    chatbot = pipeline("text-generation", model="aubmindlab/aragpt2-base")
    response = chatbot(
        text,
        max_length=100,
        num_return_sequences=1,
        pad_token_id=50256
    )
    return response[0]['generated_text']

# تحويل النص إلى صوت
async def text_to_speech(text):
    inputs = tts_tokenizer(text, return_tensors="pt")
    
    with torch.no_grad():
        output = tts_model(**inputs)
    
    waveform = output.waveform[0].numpy()
    torchaudio.save("bot_response.wav", torch.Tensor(waveform), tts_model.config.sampling_rate)

# تهيئة التطبيق
if __name__ == "__main__":
    TOKEN = os.getenv("TELEGRAM_TOKEN")
    application = Application.builder().token(TOKEN).build()
    application.add_handler(MessageHandler(filters.VOICE, process_voice))
    application.run_polling()