Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -11,26 +11,26 @@ from telegram.ext import ApplicationBuilder, MessageHandler, filters
|
|
11 |
from transformers import pipeline, AutoTokenizer, VitsModel
|
12 |
from huggingface_hub import login
|
13 |
|
14 |
-
# ===== تهيئة التوكن
|
15 |
login(token=os.getenv("HF_TOKEN"))
|
16 |
|
17 |
-
# =====
|
18 |
logging.basicConfig(
|
19 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
20 |
level=logging.INFO
|
21 |
)
|
22 |
logger = logging.getLogger(__name__)
|
23 |
|
24 |
-
# =====
|
25 |
try:
|
26 |
-
# 1. نموذج التعرف على
|
27 |
asr_pipeline = pipeline(
|
28 |
"automatic-speech-recognition",
|
29 |
model="jonatasgrosman/wav2vec2-large-xlsr-53-arabic",
|
30 |
token=os.getenv("HF_TOKEN")
|
31 |
)
|
32 |
|
33 |
-
# 2. نموذج توليف الصوت
|
34 |
tts_tokenizer = AutoTokenizer.from_pretrained(
|
35 |
"facebook/mms-tts-ara",
|
36 |
token=os.getenv("HF_TOKEN")
|
@@ -46,6 +46,7 @@ except Exception as e:
|
|
46 |
|
47 |
# ===== دوال معالجة الصوت =====
|
48 |
def enhance_audio(input_path: str, output_path: str) -> bool:
|
|
|
49 |
try:
|
50 |
audio = AudioSegment.from_wav(input_path)
|
51 |
audio = audio.low_pass_filter(3000)
|
@@ -55,10 +56,11 @@ def enhance_audio(input_path: str, output_path: str) -> bool:
|
|
55 |
audio.export(output_path, format="wav")
|
56 |
return True
|
57 |
except Exception as e:
|
58 |
-
logger.error(f"
|
59 |
return False
|
60 |
|
61 |
async def speech_to_text(audio_path: str) -> str:
|
|
|
62 |
try:
|
63 |
audio, sr = librosa.load(audio_path, sr=16000)
|
64 |
sf.write("temp.wav", audio, sr)
|
@@ -69,6 +71,7 @@ async def speech_to_text(audio_path: str) -> str:
|
|
69 |
return ""
|
70 |
|
71 |
async def generate_response(text: str) -> str:
|
|
|
72 |
try:
|
73 |
chatbot = pipeline(
|
74 |
"text-generation",
|
@@ -84,9 +87,10 @@ async def generate_response(text: str) -> str:
|
|
84 |
return response[0]['generated_text']
|
85 |
except Exception as e:
|
86 |
logger.error(f"فشل توليد الرد: {str(e)}")
|
87 |
-
return "
|
88 |
|
89 |
async def text_to_speech(text: str) -> None:
|
|
|
90 |
try:
|
91 |
inputs = tts_tokenizer(text, return_tensors="pt")
|
92 |
with torch.no_grad():
|
@@ -96,26 +100,29 @@ async def text_to_speech(text: str) -> None:
|
|
96 |
except Exception as e:
|
97 |
logger.error(f"فشل تحويل النص إلى صوت: {str(e)}")
|
98 |
|
99 |
-
# ===== الدالة الرئيسية
|
100 |
async def process_voice(update: Update, context):
|
101 |
try:
|
|
|
102 |
voice_file = await update.message.voice.get_file()
|
103 |
await voice_file.download_to_drive("user_voice.ogg")
|
104 |
|
|
|
105 |
user_text = await speech_to_text("user_voice.ogg")
|
106 |
bot_response = await generate_response(user_text)
|
107 |
await text_to_speech(bot_response)
|
108 |
|
|
|
109 |
if enhance_audio("bot_response.wav", "bot_response_enhanced.wav"):
|
110 |
await update.message.reply_voice("bot_response_enhanced.wav")
|
111 |
else:
|
112 |
await update.message.reply_voice("bot_response.wav")
|
113 |
|
114 |
except Exception as e:
|
115 |
-
logger.error(f"خطأ
|
116 |
-
await update.message.reply_text("⚠️ حدث خطأ
|
117 |
|
118 |
-
# ===== التشغيل الرئيسي
|
119 |
async def main():
|
120 |
application = ApplicationBuilder().token(os.getenv("TELEGRAM_TOKEN")).build()
|
121 |
application.add_handler(MessageHandler(filters.VOICE, process_voice))
|
|
|
11 |
from transformers import pipeline, AutoTokenizer, VitsModel
|
12 |
from huggingface_hub import login
|
13 |
|
14 |
+
# ===== تهيئة التوكن =====
|
15 |
login(token=os.getenv("HF_TOKEN"))
|
16 |
|
17 |
+
# ===== إعدادات النظام =====
|
18 |
logging.basicConfig(
|
19 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
20 |
level=logging.INFO
|
21 |
)
|
22 |
logger = logging.getLogger(__name__)
|
23 |
|
24 |
+
# ===== تحميل النماذج =====
|
25 |
try:
|
26 |
+
# 1. نموذج التعرف على الصوت (ASR)
|
27 |
asr_pipeline = pipeline(
|
28 |
"automatic-speech-recognition",
|
29 |
model="jonatasgrosman/wav2vec2-large-xlsr-53-arabic",
|
30 |
token=os.getenv("HF_TOKEN")
|
31 |
)
|
32 |
|
33 |
+
# 2. نموذج توليف الصوت (TTS)
|
34 |
tts_tokenizer = AutoTokenizer.from_pretrained(
|
35 |
"facebook/mms-tts-ara",
|
36 |
token=os.getenv("HF_TOKEN")
|
|
|
46 |
|
47 |
# ===== دوال معالجة الصوت =====
|
48 |
def enhance_audio(input_path: str, output_path: str) -> bool:
|
49 |
+
"""تحسين جودة الملف الصوتي"""
|
50 |
try:
|
51 |
audio = AudioSegment.from_wav(input_path)
|
52 |
audio = audio.low_pass_filter(3000)
|
|
|
56 |
audio.export(output_path, format="wav")
|
57 |
return True
|
58 |
except Exception as e:
|
59 |
+
logger.error(f"خطأ في تحسين الصوت: {str(e)}")
|
60 |
return False
|
61 |
|
62 |
async def speech_to_text(audio_path: str) -> str:
|
63 |
+
"""تحويل الصوت إلى نص"""
|
64 |
try:
|
65 |
audio, sr = librosa.load(audio_path, sr=16000)
|
66 |
sf.write("temp.wav", audio, sr)
|
|
|
71 |
return ""
|
72 |
|
73 |
async def generate_response(text: str) -> str:
|
74 |
+
"""توليد رد الذكاء الاصطناعي"""
|
75 |
try:
|
76 |
chatbot = pipeline(
|
77 |
"text-generation",
|
|
|
87 |
return response[0]['generated_text']
|
88 |
except Exception as e:
|
89 |
logger.error(f"فشل توليد الرد: {str(e)}")
|
90 |
+
return "حدث خطأ في توليد الرد."
|
91 |
|
92 |
async def text_to_speech(text: str) -> None:
|
93 |
+
"""تحويل النص إلى صوت"""
|
94 |
try:
|
95 |
inputs = tts_tokenizer(text, return_tensors="pt")
|
96 |
with torch.no_grad():
|
|
|
100 |
except Exception as e:
|
101 |
logger.error(f"فشل تحويل النص إلى صوت: {str(e)}")
|
102 |
|
103 |
+
# ===== الدالة الرئيسية =====
|
104 |
async def process_voice(update: Update, context):
|
105 |
try:
|
106 |
+
# تحميل الصوت
|
107 |
voice_file = await update.message.voice.get_file()
|
108 |
await voice_file.download_to_drive("user_voice.ogg")
|
109 |
|
110 |
+
# معالجة الصوت
|
111 |
user_text = await speech_to_text("user_voice.ogg")
|
112 |
bot_response = await generate_response(user_text)
|
113 |
await text_to_speech(bot_response)
|
114 |
|
115 |
+
# إرسال الرد
|
116 |
if enhance_audio("bot_response.wav", "bot_response_enhanced.wav"):
|
117 |
await update.message.reply_voice("bot_response_enhanced.wav")
|
118 |
else:
|
119 |
await update.message.reply_voice("bot_response.wav")
|
120 |
|
121 |
except Exception as e:
|
122 |
+
logger.error(f"خطأ غير متوقع: {str(e)}")
|
123 |
+
await update.message.reply_text("⚠️ عذرًا، حدث خطأ في المعالجة.")
|
124 |
|
125 |
+
# ===== التشغيل الرئيسي =====
|
126 |
async def main():
|
127 |
application = ApplicationBuilder().token(os.getenv("TELEGRAM_TOKEN")).build()
|
128 |
application.add_handler(MessageHandler(filters.VOICE, process_voice))
|