Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,32 +1,46 @@
|
|
1 |
import os
|
2 |
import gradio as gr
|
3 |
-
from google import
|
4 |
-
from google.genai import types # імпартуем для выкарыстання GenerateContentConfig
|
5 |
import mimetypes
|
6 |
from pydub import AudioSegment
|
7 |
|
8 |
# Атрыманне ключоў і мадэляў з пераменных асяроддзя
|
9 |
GEMINI_API_KEY = os.getenv("gemini")
|
10 |
-
MODEL_NAME_TH = os.getenv("modTH")
|
11 |
-
MODEL_NAME = os.getenv("mod")
|
12 |
-
P = os.getenv("p")
|
|
|
|
|
|
|
|
|
13 |
|
14 |
# Стварэнне кліента з новым SDK
|
15 |
-
client =
|
16 |
|
17 |
def transcribe_audio(audio_file):
|
|
|
18 |
try:
|
19 |
mime_type, _ = mimetypes.guess_type(audio_file)
|
20 |
if mime_type is None:
|
21 |
return "Немагчыма вызначыць тып файла. Падтрымліваюцца толькі аўдыяфайлы."
|
22 |
with open(audio_file, "rb") as f:
|
23 |
audio_data = f.read()
|
24 |
-
|
25 |
-
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
model=MODEL_NAME_TH,
|
28 |
-
contents=
|
29 |
-
|
30 |
)
|
31 |
if response.text:
|
32 |
transcript = response.text.strip()
|
@@ -36,7 +50,8 @@ def transcribe_audio(audio_file):
|
|
36 |
except FileNotFoundError:
|
37 |
return "Памылка: Файл не знойдзены."
|
38 |
except Exception as e:
|
39 |
-
return f"Нечаканая
|
|
|
40 |
|
41 |
def fix_subtitles_format(transcript):
|
42 |
"""
|
@@ -44,13 +59,15 @@ def fix_subtitles_format(transcript):
|
|
44 |
"""
|
45 |
try:
|
46 |
prompt_fix = (
|
47 |
-
|
48 |
f"У адказ напішы толькі субцітры: {transcript}"
|
49 |
)
|
50 |
-
|
|
|
|
|
51 |
model=MODEL_NAME,
|
52 |
-
contents=prompt_fix,
|
53 |
-
|
54 |
)
|
55 |
if response_fix.text:
|
56 |
fixed_transcript = response_fix.text.strip()
|
@@ -60,7 +77,9 @@ def fix_subtitles_format(transcript):
|
|
60 |
except Exception as e:
|
61 |
return transcript
|
62 |
|
|
|
63 |
def create_srt(transcript, filename="subtitles.srt"):
|
|
|
64 |
try:
|
65 |
with open(filename, "w", encoding="utf-8") as f:
|
66 |
f.write(transcript)
|
@@ -68,7 +87,9 @@ def create_srt(transcript, filename="subtitles.srt"):
|
|
68 |
except Exception as e:
|
69 |
return f"Памылка пры запісе SRT-файла: {str(e)}", None
|
70 |
|
|
|
71 |
def process_audio(audio):
|
|
|
72 |
transcript = transcribe_audio(audio)
|
73 |
if transcript.startswith("Памылка"):
|
74 |
return transcript, None
|
@@ -77,7 +98,9 @@ def process_audio(audio):
|
|
77 |
text, srt_file = create_srt(fixed_transcript)
|
78 |
return text, srt_file
|
79 |
|
|
|
80 |
def extract_audio_from_video(video_file):
|
|
|
81 |
try:
|
82 |
audio = AudioSegment.from_file(video_file)
|
83 |
audio_path = "extracted_audio.mp3"
|
@@ -86,13 +109,17 @@ def extract_audio_from_video(video_file):
|
|
86 |
except Exception as e:
|
87 |
return None, f"Памылка пры выдзяленні аўдыі з відэафайла: {str(e)}"
|
88 |
|
|
|
89 |
def process_video(video):
|
|
|
90 |
audio_path, error = extract_audio_from_video(video)
|
91 |
if error:
|
92 |
return error, None
|
93 |
return process_audio(audio_path)
|
94 |
|
|
|
95 |
def process_file(audio, video):
|
|
|
96 |
if audio is not None:
|
97 |
return process_audio(audio)
|
98 |
elif video is not None:
|
@@ -100,28 +127,36 @@ def process_file(audio, video):
|
|
100 |
else:
|
101 |
return "Няма файла для апрацоўкі.", None
|
102 |
|
|
|
103 |
def update_on_audio_change(audio):
|
|
|
104 |
if audio is not None:
|
105 |
return gr.update(value=None, interactive=False)
|
106 |
else:
|
107 |
return gr.update(interactive=True)
|
108 |
|
|
|
109 |
def update_on_video_change(video):
|
|
|
110 |
if video is not None:
|
111 |
return gr.update(value=None, interactive=False)
|
112 |
else:
|
113 |
return gr.update(interactive=True)
|
114 |
|
|
|
115 |
def translate_transcript(transcript, target_language):
|
|
|
116 |
try:
|
117 |
prompt_text = (
|
118 |
f"перакладзі толькі тэксты субцітраў на {target_language} мову. Астатня пакінь як ёсць.\n"
|
119 |
f"Тэкст:\n{transcript}"
|
120 |
)
|
121 |
-
|
|
|
|
|
122 |
model=MODEL_NAME,
|
123 |
-
contents=prompt_text,
|
124 |
-
|
125 |
)
|
126 |
if response.text:
|
127 |
translated = response.text.strip()
|
@@ -134,6 +169,7 @@ def translate_transcript(transcript, target_language):
|
|
134 |
except Exception as e:
|
135 |
return f"Памылка пры перакладзе: {str(e)}", None
|
136 |
|
|
|
137 |
with gr.Blocks() as demo:
|
138 |
gr.Markdown("# Транскрыпцыя аўдыя для беларускай мовы")
|
139 |
gr.Markdown(
|
@@ -149,12 +185,12 @@ with gr.Blocks() as demo:
|
|
149 |
video_input = gr.Video(label="Відэафайл")
|
150 |
audio_input.change(fn=update_on_audio_change, inputs=audio_input, outputs=video_input)
|
151 |
video_input.change(fn=update_on_video_change, inputs=video_input, outputs=audio_input)
|
152 |
-
|
153 |
btn = gr.Button("Апрацаваць")
|
154 |
transcript_output = gr.Textbox(label="Транскрыпцыя", lines=10)
|
155 |
file_output = gr.File(label="SRT-файл")
|
156 |
btn.click(fn=process_file, inputs=[audio_input, video_input], outputs=[transcript_output, file_output])
|
157 |
-
|
158 |
gr.Markdown("## Пераклад субцітраў")
|
159 |
with gr.Row():
|
160 |
language_dropdown = gr.Dropdown(
|
@@ -170,4 +206,4 @@ with gr.Blocks() as demo:
|
|
170 |
outputs=[translation_output, translation_file_output]
|
171 |
)
|
172 |
|
173 |
-
demo.launch()
|
|
|
1 |
import os
|
2 |
import gradio as gr
|
3 |
+
from google.generativeai import Client, GenerationConfig # Import GenerationConfig directly
|
|
|
4 |
import mimetypes
|
5 |
from pydub import AudioSegment
|
6 |
|
7 |
# Атрыманне ключоў і мадэляў з пераменных асяроддзя
|
8 |
GEMINI_API_KEY = os.getenv("gemini")
|
9 |
+
MODEL_NAME_TH = os.getenv("modTH")
|
10 |
+
MODEL_NAME = os.getenv("mod")
|
11 |
+
P = os.getenv("p")
|
12 |
+
|
13 |
+
# Праверка наяўнасці ключа API
|
14 |
+
if not GEMINI_API_KEY:
|
15 |
+
raise ValueError("Памылка: пераменная асяроддзя 'gemini' не зададзена. Калі ласка, задайце ключ API.")
|
16 |
|
17 |
# Стварэнне кліента з новым SDK
|
18 |
+
client = Client(api_key=GEMINI_API_KEY) # use Client instead of genai.Client
|
19 |
|
20 |
def transcribe_audio(audio_file):
|
21 |
+
"""Транскрыбіруе аўдыёфайл з дапамогай Gemini API."""
|
22 |
try:
|
23 |
mime_type, _ = mimetypes.guess_type(audio_file)
|
24 |
if mime_type is None:
|
25 |
return "Немагчыма вызначыць тып файла. Падтрымліваюцца толькі аўдыяфайлы."
|
26 |
with open(audio_file, "rb") as f:
|
27 |
audio_data = f.read()
|
28 |
+
|
29 |
+
# Падрыхтоўка запыту з prompt і аўдыё
|
30 |
+
contents = [
|
31 |
+
{"parts": [{"text": P}]}, # Prompt з пераменнай P
|
32 |
+
{"parts": [{"mime_type": mime_type, "data": audio_data}]}
|
33 |
+
]
|
34 |
+
generation_config = GenerationConfig( # Use GenerationConfig
|
35 |
+
# Добавьте параметры для управления генерацией (напрыклад, temperature, top_p)
|
36 |
+
# temperature=0.9, # Напрыклад, для больш творчага выніку
|
37 |
+
# top_p=0.8,
|
38 |
+
)
|
39 |
+
|
40 |
+
response = client.generate_content(
|
41 |
model=MODEL_NAME_TH,
|
42 |
+
contents=contents,
|
43 |
+
generation_config=generation_config,
|
44 |
)
|
45 |
if response.text:
|
46 |
transcript = response.text.strip()
|
|
|
50 |
except FileNotFoundError:
|
51 |
return "Памылка: Файл не знойдзены."
|
52 |
except Exception as e:
|
53 |
+
return f"Нечаканая памылка пры транскрыбаванні: {str(e)}"
|
54 |
+
|
55 |
|
56 |
def fix_subtitles_format(transcript):
|
57 |
"""
|
|
|
59 |
"""
|
60 |
try:
|
61 |
prompt_fix = (
|
62 |
+
"Не змяняй тэксты, выправі толькі часовы фармат у субцітрах на правільны, вось прыклад 00:00:01,589 \n"
|
63 |
f"У адказ напішы толькі субцітры: {transcript}"
|
64 |
)
|
65 |
+
generation_config = GenerationConfig() # Use GenerationConfig
|
66 |
+
|
67 |
+
response_fix = client.generate_content(
|
68 |
model=MODEL_NAME,
|
69 |
+
contents=[{"parts": [{"text": prompt_fix}]}],
|
70 |
+
generation_config=generation_config,
|
71 |
)
|
72 |
if response_fix.text:
|
73 |
fixed_transcript = response_fix.text.strip()
|
|
|
77 |
except Exception as e:
|
78 |
return transcript
|
79 |
|
80 |
+
|
81 |
def create_srt(transcript, filename="subtitles.srt"):
|
82 |
+
"""Стварае SRT-файл з дадзенай транскрыпцыяй."""
|
83 |
try:
|
84 |
with open(filename, "w", encoding="utf-8") as f:
|
85 |
f.write(transcript)
|
|
|
87 |
except Exception as e:
|
88 |
return f"Памылка пры запісе SRT-файла: {str(e)}", None
|
89 |
|
90 |
+
|
91 |
def process_audio(audio):
|
92 |
+
"""Апрацоўвае асобны аўдыёфайл."""
|
93 |
transcript = transcribe_audio(audio)
|
94 |
if transcript.startswith("Памылка"):
|
95 |
return transcript, None
|
|
|
98 |
text, srt_file = create_srt(fixed_transcript)
|
99 |
return text, srt_file
|
100 |
|
101 |
+
|
102 |
def extract_audio_from_video(video_file):
|
103 |
+
"""Выдзяляе аўдыё з відэафайла."""
|
104 |
try:
|
105 |
audio = AudioSegment.from_file(video_file)
|
106 |
audio_path = "extracted_audio.mp3"
|
|
|
109 |
except Exception as e:
|
110 |
return None, f"Памылка пры выдзяленні аўдыі з відэафайла: {str(e)}"
|
111 |
|
112 |
+
|
113 |
def process_video(video):
|
114 |
+
"""Апрацоўвае відэафайл."""
|
115 |
audio_path, error = extract_audio_from_video(video)
|
116 |
if error:
|
117 |
return error, None
|
118 |
return process_audio(audio_path)
|
119 |
|
120 |
+
|
121 |
def process_file(audio, video):
|
122 |
+
"""Асноўная функцыя апрацоўкі, якая вызначае, што рабіць у залежнасці ад таго, які файл загружаны."""
|
123 |
if audio is not None:
|
124 |
return process_audio(audio)
|
125 |
elif video is not None:
|
|
|
127 |
else:
|
128 |
return "Няма файла для апрацоўкі.", None
|
129 |
|
130 |
+
|
131 |
def update_on_audio_change(audio):
|
132 |
+
"""Абнаўляе інтэрфейс, калі змяняецца аўдыёфайл."""
|
133 |
if audio is not None:
|
134 |
return gr.update(value=None, interactive=False)
|
135 |
else:
|
136 |
return gr.update(interactive=True)
|
137 |
|
138 |
+
|
139 |
def update_on_video_change(video):
|
140 |
+
"""Абнаўляе інтэрфейс, калі змяняецца відэафайл."""
|
141 |
if video is not None:
|
142 |
return gr.update(value=None, interactive=False)
|
143 |
else:
|
144 |
return gr.update(interactive=True)
|
145 |
|
146 |
+
|
147 |
def translate_transcript(transcript, target_language):
|
148 |
+
"""Перакладае транскрыпцыю на абраную мову."""
|
149 |
try:
|
150 |
prompt_text = (
|
151 |
f"перакладзі толькі тэксты субцітраў на {target_language} мову. Астатня пакінь як ёсць.\n"
|
152 |
f"Тэкст:\n{transcript}"
|
153 |
)
|
154 |
+
generation_config = GenerationConfig() # Use GenerationConfig
|
155 |
+
|
156 |
+
response = client.generate_content(
|
157 |
model=MODEL_NAME,
|
158 |
+
contents=[{"parts": [{"text": prompt_text}]}],
|
159 |
+
generation_config=generation_config,
|
160 |
)
|
161 |
if response.text:
|
162 |
translated = response.text.strip()
|
|
|
169 |
except Exception as e:
|
170 |
return f"Памылка пры перакладзе: {str(e)}", None
|
171 |
|
172 |
+
|
173 |
with gr.Blocks() as demo:
|
174 |
gr.Markdown("# Транскрыпцыя аўдыя для беларускай мовы")
|
175 |
gr.Markdown(
|
|
|
185 |
video_input = gr.Video(label="Відэафайл")
|
186 |
audio_input.change(fn=update_on_audio_change, inputs=audio_input, outputs=video_input)
|
187 |
video_input.change(fn=update_on_video_change, inputs=video_input, outputs=audio_input)
|
188 |
+
|
189 |
btn = gr.Button("Апрацаваць")
|
190 |
transcript_output = gr.Textbox(label="Транскрыпцыя", lines=10)
|
191 |
file_output = gr.File(label="SRT-файл")
|
192 |
btn.click(fn=process_file, inputs=[audio_input, video_input], outputs=[transcript_output, file_output])
|
193 |
+
|
194 |
gr.Markdown("## Пераклад субцітраў")
|
195 |
with gr.Row():
|
196 |
language_dropdown = gr.Dropdown(
|
|
|
206 |
outputs=[translation_output, translation_file_output]
|
207 |
)
|
208 |
|
209 |
+
demo.launch()
|