KIMOSSINO commited on
Commit
777a4e8
·
verified ·
1 Parent(s): 5d2171a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -201
app.py CHANGED
@@ -1,201 +0,0 @@
1
- import gradio as gr
2
- import whisper
3
- import os
4
- import asyncio
5
- import edge_tts
6
- from transformers import pipeline
7
- from deep_translator import GoogleTranslator
8
- from docx import Document
9
- import tempfile
10
- from datetime import datetime
11
- import logging
12
- from pydub import AudioSegment
13
-
14
- # إعداد التسجيل
15
- logging.basicConfig(
16
- level=logging.INFO,
17
- format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
18
- handlers=[
19
- logging.FileHandler("app.log"),
20
- logging.StreamHandler(),
21
- ],
22
- )
23
- logger = logging.getLogger(__name__)
24
-
25
- # قائمة اللغات المدعومة
26
- SUPPORTED_LANGUAGES = {
27
- "ar": "العربية",
28
- "en": "English",
29
- "fr": "Français",
30
- "es": "Español",
31
- "de": "Deutsch",
32
- }
33
-
34
- # تعيين أصوات لكل لغة
35
- VOICE_MAPPINGS = {
36
- "ar": "ar-EG-ShakirNeural",
37
- "en": "en-US-EricNeural",
38
- "fr": "fr-FR-HenriNeural",
39
- "es": "es-ES-AlvaroNeural",
40
- "de": "de-DE-ConradNeural",
41
- }
42
-
43
- # تحديد اللغات RTL
44
- RTL_LANGUAGES = ["ar"]
45
-
46
- # وظيفة تنظيف النص
47
- def clean_text(text):
48
- return (
49
- text.replace("’", "'")
50
- .replace("«", "")
51
- .replace("»", "")
52
- .replace("\n", " ")
53
- .strip()
54
- )
55
-
56
- # وظيفة توليد الصوت
57
- async def generate_speech(text, lang):
58
- """توليد الصوت باستخدام edge-tts"""
59
- try:
60
- voice = VOICE_MAPPINGS.get(lang, "en-US-EricNeural")
61
- communicate = edge_tts.Communicate(text, voice)
62
- audio_path = tempfile.mktemp(suffix=".mp3")
63
- await communicate.save(audio_path)
64
-
65
- if os.path.exists(audio_path) and os.path.getsize(audio_path) > 0:
66
- logger.info(f"تم إنشاء ملف صوتي: {audio_path}")
67
- return audio_path
68
- else:
69
- logger.error("فشل إنشاء ملف صوتي صالح")
70
- return None
71
-
72
- except Exception as e:
73
- logger.error(f"خطأ في توليد الصوت: {str(e)}")
74
- return None
75
-
76
- # تحويل النص إلى صوت
77
- def text_to_speech(text, lang):
78
- if not text:
79
- logger.warning("لم يتم تقديم نص للتحويل إلى صوت")
80
- return None
81
-
82
- try:
83
- text = clean_text(text)
84
- max_length = 1000
85
- text_parts = [text[i : i + max_length] for i in range(0, len(text), max_length)]
86
-
87
- audio_files = []
88
- for part in text_parts:
89
- audio_path = asyncio.run(generate_speech(part, lang))
90
- if audio_path:
91
- audio_files.append(audio_path)
92
-
93
- if len(audio_files) == 1:
94
- return audio_files[0]
95
-
96
- final_audio = AudioSegment.from_mp3(audio_files[0])
97
- for audio_file in audio_files[1:]:
98
- final_audio += AudioSegment.from_mp3(audio_file)
99
-
100
- final_path = tempfile.mktemp(suffix=".mp3")
101
- final_audio.export(final_path, format="mp3")
102
-
103
- for file in audio_files:
104
- os.remove(file)
105
-
106
- return final_path
107
-
108
- except Exception as e:
109
- logger.error(f"خطأ في تحويل النص إلى صوت: {str(e)}")
110
- return None
111
-
112
- # الترجمة
113
- def translate_text(text, source_lang, target_lang):
114
- if source_lang == target_lang:
115
- return text
116
-
117
- try:
118
- translator = GoogleTranslator(source=source_lang, target=target_lang)
119
- max_length = 5000
120
- text_parts = [text[i : i + max_length] for i in range(0, len(text), max_length)]
121
- translated_parts = [translator.translate(part) for part in text_parts]
122
- return " ".join(translated_parts)
123
-
124
- except Exception as e:
125
- logger.error(f"خطأ في الترجمة: {str(e)}")
126
- return f"خطأ في الترجمة: {str(e)}"
127
-
128
- # معالجة الفيديو
129
- def process_video(video, source_lang="en", target_lang="ar"):
130
- if video is None:
131
- return {
132
- "error": "الرجاء رفع ملف فيديو",
133
- "original": "",
134
- "translated": "",
135
- }
136
-
137
- try:
138
- temp_path = video.name
139
- model = whisper.load_model("base")
140
- result = model.transcribe(temp_path, language=source_lang)
141
- transcribed_text = result["text"]
142
- translated_text = translate_text(transcribed_text, source_lang, target_lang)
143
- return {
144
- "error": None,
145
- "original": transcribed_text,
146
- "translated": translated_text,
147
- }
148
-
149
- except Exception as e:
150
- logger.error(f"خطأ في معالجة الفيديو: {str(e)}")
151
- return {
152
- "error": f"حدث خطأ: {str(e)}",
153
- "original": "",
154
- "translated": "",
155
- }
156
-
157
- # إنشاء الواجهة
158
- def create_ui():
159
- with gr.Blocks() as demo:
160
- gr.Markdown("# 🎥 تحويل الفيديو إلى نصوص وصوت")
161
- with gr.Row():
162
- video_input = gr.File(label="📁 رفع فيديو", file_types=["video"])
163
- source_lang = gr.Dropdown(
164
- choices=list(SUPPORTED_LANGUAGES.keys()),
165
- value="en",
166
- label="🗣️ لغة الفيديو الأصلية",
167
- )
168
- target_lang = gr.Dropdown(
169
- choices=list(SUPPORTED_LANGUAGES.keys()),
170
- value="ar",
171
- label="🌐 لغة الترجمة",
172
- )
173
- process_btn = gr.Button("🎯 معالجة الفيديو")
174
-
175
- with gr.Tabs():
176
- with gr.TabItem("النص الأصلي"):
177
- original_text = gr.Textbox(label="النص المستخرج", lines=10)
178
- original_audio = gr.Audio(label="الصوت")
179
- with gr.TabItem("النص المترجم"):
180
- translated_text = gr.Textbox(label="النص المترجم", lines=10)
181
- translated_audio = gr.Audio(label="الصوت")
182
-
183
- def update_ui(video, src_lang, tgt_lang):
184
- result = process_video(video, src_lang, tgt_lang)
185
- return {
186
- original_text: result["original"],
187
- translated_text: result["translated"],
188
- }
189
-
190
- process_btn.click(
191
- fn=update_ui,
192
- inputs=[video_input, source_lang, target_lang],
193
- outputs=[original_text, translated_text],
194
- )
195
-
196
- return demo
197
-
198
-
199
- if __name__ == "__main__":
200
- demo = create_ui()
201
- demo.launch()