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+
import spaces
|
2 |
+
import torch
|
3 |
+
import gradio as gr
|
4 |
+
from transformers import pipeline
|
5 |
+
from huggingface_hub import InferenceClient
|
6 |
import os
|
7 |
+
import numpy as np
|
8 |
+
from pydub import AudioSegment
|
9 |
+
import tempfile
|
10 |
+
import math
|
11 |
+
|
12 |
+
# Hugging Face ν ν° μ€μ
|
13 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
14 |
+
if not HF_TOKEN:
|
15 |
+
raise ValueError("HF_TOKEN νκ²½ λ³μκ° μ€μ λμ§ μμμ΅λλ€.")
|
16 |
+
|
17 |
+
MODEL_NAME = "openai/whisper-large-v3-turbo"
|
18 |
+
BATCH_SIZE = 8
|
19 |
+
FILE_LIMIT_MB = 1000
|
20 |
+
CHUNK_LENGTH = 10 * 60 # 10λΆ λ¨μλ‘ λΆν
|
21 |
+
|
22 |
+
device = 0 if torch.cuda.is_available() else "cpu"
|
23 |
+
|
24 |
+
# Whisper νμ΄νλΌμΈ μ΄κΈ°ν
|
25 |
+
pipe = pipeline(
|
26 |
+
task="automatic-speech-recognition",
|
27 |
+
model=MODEL_NAME,
|
28 |
+
chunk_length_s=30,
|
29 |
+
device=device,
|
30 |
+
token=HF_TOKEN
|
31 |
+
)
|
32 |
+
|
33 |
+
# Hugging Face μΆλ‘ ν΄λΌμ΄μΈνΈ μ€μ
|
34 |
+
hf_client = InferenceClient(
|
35 |
+
"CohereForAI/c4ai-command-r-plus-08-2024",
|
36 |
+
token=HF_TOKEN
|
37 |
+
)
|
38 |
+
|
39 |
+
def split_audio(audio_path, chunk_length=CHUNK_LENGTH):
|
40 |
+
"""μ€λμ€ νμΌμ μ²ν¬λ‘ λΆν """
|
41 |
+
audio = AudioSegment.from_file(audio_path)
|
42 |
+
duration = len(audio) / 1000 # μ΄ λ¨μ λ³ν
|
43 |
+
chunks = []
|
44 |
+
|
45 |
+
# μ²ν¬ κ°μ κ³μ°
|
46 |
+
num_chunks = math.ceil(duration / chunk_length)
|
47 |
+
|
48 |
+
for i in range(num_chunks):
|
49 |
+
start_time = i * chunk_length * 1000 # milliseconds
|
50 |
+
end_time = min((i + 1) * chunk_length * 1000, len(audio))
|
51 |
+
|
52 |
+
chunk = audio[start_time:end_time]
|
53 |
+
|
54 |
+
# μμ νμΌλ‘ μ μ₯
|
55 |
+
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as temp_file:
|
56 |
+
chunk.export(temp_file.name, format='wav')
|
57 |
+
chunks.append(temp_file.name)
|
58 |
+
|
59 |
+
return chunks, num_chunks
|
60 |
+
|
61 |
+
def translate_to_korean(text):
|
62 |
+
"""μμ΄ ν
μ€νΈλ₯Ό νκΈλ‘ λ²μ"""
|
63 |
+
try:
|
64 |
+
prompt = f"""λ€μ μμ΄ ν
μ€νΈλ₯Ό μμ°μ€λ¬μ΄ νκ΅μ΄λ‘ λ²μν΄μ£ΌμΈμ.
|
65 |
+
μμ΄: {text}
|
66 |
+
νκ΅μ΄:"""
|
67 |
+
|
68 |
+
response = hf_client.text_generation(
|
69 |
+
prompt=prompt,
|
70 |
+
max_new_tokens=4000,
|
71 |
+
temperature=0.3,
|
72 |
+
top_p=0.9,
|
73 |
+
repetition_penalty=1.2,
|
74 |
+
stop=["μμ΄:", "νκ΅μ΄:", "\n"]
|
75 |
+
)
|
76 |
+
|
77 |
+
translated_text = str(response)
|
78 |
+
if "νκ΅μ΄:" in translated_text:
|
79 |
+
translated_text = translated_text.split("νκ΅μ΄:")[1].strip()
|
80 |
+
|
81 |
+
return translated_text
|
82 |
+
except Exception as e:
|
83 |
+
print(f"λ²μ μ€ μ€λ₯ λ°μ: {str(e)}")
|
84 |
+
return text
|
85 |
+
|
86 |
+
def process_chunk(chunk_path, task):
|
87 |
+
"""κ°λ³ μ²ν¬ μ²λ¦¬"""
|
88 |
+
if task == "translate":
|
89 |
+
generate_kwargs = {
|
90 |
+
"task": "transcribe",
|
91 |
+
"language": "en",
|
92 |
+
"forced_decoder_ids": None
|
93 |
+
}
|
94 |
+
else:
|
95 |
+
generate_kwargs = {
|
96 |
+
"task": "transcribe",
|
97 |
+
"language": "ko",
|
98 |
+
"forced_decoder_ids": None
|
99 |
+
}
|
100 |
+
|
101 |
+
try:
|
102 |
+
result = pipe(
|
103 |
+
inputs=chunk_path,
|
104 |
+
batch_size=BATCH_SIZE,
|
105 |
+
generate_kwargs=generate_kwargs,
|
106 |
+
return_timestamps=True
|
107 |
+
)
|
108 |
+
|
109 |
+
os.unlink(chunk_path)
|
110 |
+
text = result["text"]
|
111 |
+
|
112 |
+
if task == "translate":
|
113 |
+
text = translate_to_korean(text)
|
114 |
+
|
115 |
+
return text
|
116 |
+
except Exception as e:
|
117 |
+
print(f"μ²ν¬ μ²λ¦¬ μ€ μ€λ₯ λ°μ: {str(e)}")
|
118 |
+
raise e
|
119 |
+
|
120 |
+
@spaces.GPU
|
121 |
+
def transcribe_audio(audio_input, task, progress=gr.Progress()):
|
122 |
+
if audio_input is None:
|
123 |
+
raise gr.Error("μ€λμ€ νμΌμ΄ μ μΆλμ§ μμμ΅λλ€!")
|
124 |
+
|
125 |
+
try:
|
126 |
+
chunks, num_chunks = split_audio(audio_input)
|
127 |
+
progress(0, desc="μ€λμ€ νμΌ λΆν μλ£")
|
128 |
+
|
129 |
+
transcribed_texts = []
|
130 |
+
for i, chunk in enumerate(chunks):
|
131 |
+
try:
|
132 |
+
chunk_text = process_chunk(chunk, task)
|
133 |
+
transcribed_texts.append(chunk_text)
|
134 |
+
progress((i + 1) / num_chunks, desc=f"μ²ν¬ {i+1}/{num_chunks} μ²λ¦¬ μ€")
|
135 |
+
except Exception as e:
|
136 |
+
print(f"μ²ν¬ {i+1} μ²λ¦¬ μ€ν¨: {str(e)}")
|
137 |
+
continue
|
138 |
+
|
139 |
+
if not transcribed_texts:
|
140 |
+
raise Exception("λͺ¨λ μ²ν¬ μ²λ¦¬μ μ€ν¨νμ΅λλ€.")
|
141 |
+
|
142 |
+
transcribed_text = " ".join(transcribed_texts)
|
143 |
+
progress(1.0, desc="μ²λ¦¬ μλ£")
|
144 |
+
return transcribed_text
|
145 |
+
|
146 |
+
except Exception as e:
|
147 |
+
error_msg = f"μμ± μ²λ¦¬ μ€ μ€λ₯κ° λ°μνμ΅λλ€: {str(e)}"
|
148 |
+
print(f"μμΈ μ€λ₯: {str(e)}")
|
149 |
+
return error_msg
|
150 |
+
|
151 |
+
# CSS μ€νμΌ
|
152 |
+
css = """
|
153 |
+
footer { visibility: hidden; }
|
154 |
+
.progress-bar { height: 15px; border-radius: 5px; }
|
155 |
+
.container { max-width: 1200px; margin: auto; padding: 20px; }
|
156 |
+
.output-text { font-size: 16px; line-height: 1.5; }
|
157 |
+
.status-display {
|
158 |
+
background: #f0f0f0;
|
159 |
+
padding: 10px;
|
160 |
+
border-radius: 5px;
|
161 |
+
margin: 10px 0;
|
162 |
+
}
|
163 |
+
"""
|
164 |
+
|
165 |
+
# νμΌ μ
λ‘λ μΈν°νμ΄μ€
|
166 |
+
file_transcribe = gr.Interface(
|
167 |
+
fn=transcribe_audio,
|
168 |
+
inputs=[
|
169 |
+
gr.Audio(
|
170 |
+
sources="upload",
|
171 |
+
type="filepath",
|
172 |
+
label="μ€λμ€ νμΌ"
|
173 |
+
),
|
174 |
+
gr.Radio(
|
175 |
+
choices=["transcribe", "translate"],
|
176 |
+
label="μμ
μ ν",
|
177 |
+
value="transcribe",
|
178 |
+
info="λ³ν: νκΈ μμ± β νκΈ ν
μ€νΈ | λ²μ: μμ΄ μμ± β νκΈ ν
μ€νΈ"
|
179 |
+
)
|
180 |
+
],
|
181 |
+
outputs=gr.Textbox(
|
182 |
+
label="λ³ν/λ²μλ ν
μ€νΈ",
|
183 |
+
lines=10,
|
184 |
+
max_lines=30,
|
185 |
+
placeholder="μμ±μ΄ ν
μ€νΈλ‘ λ³νλμ΄ μ¬κΈ°μ νμλ©λλ€...",
|
186 |
+
elem_classes="output-text"
|
187 |
+
),
|
188 |
+
title="π€ μμ± λ³ν/λ²μ AI 'λ°μμ°κΈ°'(Badassgi)",
|
189 |
+
description="""
|
190 |
+
νκΈ μμ±μ ν
μ€νΈλ‘ λ³ννκ±°λ μμ΄ μμ±μ νκΈλ‘ λ²μν μ μμ΅λλ€.
|
191 |
+
- λ³ν: νκΈ μμ± β νκΈ ν
μ€νΈ
|
192 |
+
- λ²μ: μμ΄ μμ± β νκΈ ν
μ€νΈ
|
193 |
+
""",
|
194 |
+
examples=[],
|
195 |
+
cache_examples=False,
|
196 |
+
flagging_mode="never"
|
197 |
+
)
|
198 |
+
|
199 |
+
# λ§μ΄ν¬ λ
Ήμ μΈν°νμ΄μ€
|
200 |
+
mic_transcribe = gr.Interface(
|
201 |
+
fn=transcribe_audio,
|
202 |
+
inputs=[
|
203 |
+
gr.Audio(
|
204 |
+
sources="microphone",
|
205 |
+
type="filepath",
|
206 |
+
label="λ§μ΄ν¬ λ
Ήμ"
|
207 |
+
),
|
208 |
+
gr.Radio(
|
209 |
+
choices=["transcribe", "translate"],
|
210 |
+
label="μμ
μ ν",
|
211 |
+
value="transcribe",
|
212 |
+
info="λ³ν: νκΈ μμ± β νκΈ ν
μ€νΈ | λ²μ: μμ΄ μμ± β νκΈ ν
μ€νΈ"
|
213 |
+
)
|
214 |
+
],
|
215 |
+
outputs=gr.Textbox(
|
216 |
+
label="λ³ν/λ²μλ ν
μ€νΈ",
|
217 |
+
lines=10,
|
218 |
+
max_lines=30,
|
219 |
+
elem_classes="output-text"
|
220 |
+
),
|
221 |
+
title="π€ μμ± λ³ν/λ²μ AI 'λ°μμ°κΈ°'(Badassgi)",
|
222 |
+
description="λ§μ΄ν¬λ‘ μμ±μ λ
Ήμνμ¬ ν
μ€νΈλ‘ λ³ννκ±°λ λ²μν μ μμ΅λλ€.",
|
223 |
+
flagging_mode="never"
|
224 |
+
)
|
225 |
+
|
226 |
+
# λ©μΈ μ ν리μΌμ΄μ
|
227 |
+
demo = gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", css=css)
|
228 |
+
with demo:
|
229 |
+
gr.TabbedInterface(
|
230 |
+
[file_transcribe, mic_transcribe],
|
231 |
+
["μ€λμ€ νμΌ", "λ§μ΄ν¬ λ
Ήμ"]
|
232 |
+
)
|
233 |
+
|
234 |
+
# μ ν리μΌμ΄μ
μ€ν
|
235 |
+
demo.queue().launch(
|
236 |
+
server_name="0.0.0.0",
|
237 |
+
share=True,
|
238 |
+
debug=True,
|
239 |
+
ssr_mode=False,
|
240 |
+
max_threads=3,
|
241 |
+
show_error=True
|
242 |
+
)
|