File size: 11,691 Bytes
effad1c
 
 
 
 
 
 
 
 
 
 
b3067c5
fd022eb
6bdc489
b3067c5
effad1c
6bdc489
 
 
a609646
 
6bdc489
32b3c75
a609646
 
 
32b3c75
5897b48
392a5eb
 
 
5897b48
effad1c
fd022eb
 
effad1c
 
 
 
392a5eb
effad1c
 
 
392a5eb
 
effad1c
 
a609646
 
 
392a5eb
 
fd022eb
392a5eb
a609646
effad1c
5897b48
a609646
 
effad1c
 
5897b48
 
392a5eb
5897b48
 
 
effad1c
 
a609646
 
effad1c
fd022eb
 
 
effad1c
fd022eb
392a5eb
a609646
 
 
5897b48
 
a609646
 
 
5897b48
a609646
392a5eb
a609646
 
effad1c
fd022eb
 
 
effad1c
fd022eb
effad1c
fd022eb
392a5eb
fd022eb
 
 
 
 
effad1c
 
fd022eb
effad1c
 
 
 
 
 
 
fd022eb
392a5eb
fd022eb
 
 
 
 
 
 
 
effad1c
392a5eb
 
 
a609646
2adfcbe
effad1c
 
 
 
392a5eb
 
 
 
 
a609646
effad1c
 
392a5eb
 
effad1c
392a5eb
 
 
 
a609646
392a5eb
5897b48
effad1c
392a5eb
 
effad1c
fd022eb
392a5eb
 
effad1c
 
 
 
392a5eb
 
 
 
 
 
 
 
 
 
 
 
effad1c
392a5eb
 
effad1c
392a5eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
effad1c
392a5eb
 
effad1c
392a5eb
 
 
 
 
effad1c
7cce69a
 
effad1c
392a5eb
 
 
 
 
 
5897b48
 
 
392a5eb
effad1c
a609646
effad1c
fd022eb
392a5eb
 
 
effad1c
a609646
392a5eb
 
 
 
effad1c
392a5eb
 
 
 
effad1c
 
392a5eb
 
effad1c
392a5eb
effad1c
392a5eb
effad1c
392a5eb
 
effad1c
 
 
 
 
 
 
 
392a5eb
 
effad1c
b3067c5
392a5eb
 
 
 
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
"""
SMARTok ํ•ต์‹ฌ ๋ฐ๋ชจ
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
โœ“ ํƒญ 1 : ์˜ค๋””์˜ค(๋…น์ŒยทํŒŒ์ผ) ๋‹จ๊ฑด ๋ฒˆ์—ญ + TTS ์žฌ์ƒ
โœ“ ํƒญ 2 : PDF / ์ด๋ฏธ์ง€ ๋ฒˆ์—ญ (Tesseract ์—†์œผ๋ฉด PDF๋งŒ ์•ˆ๋‚ด)
โœ“ ํƒญ 3 : ์‹ค์‹œ๊ฐ„ 1๊ฐœ ์–ธ์–ด(์„ ํƒํ˜•) ๋ฒˆ์—ญ
โœ“ ํƒญ 4 : ์‹ค์‹œ๊ฐ„ 4๊ฐœ ์–ธ์–ด(์˜ยท์ค‘(๊ฐ„)ยทํƒœยท๋Ÿฌ) ๋™์‹œ ๋ฒˆ์—ญ
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Python โ‰ฅ3.10, Gradio 4.x, OpenAI Python SDK ํ•„์š”
"""

import gradio as gr
import openai, os, io, tempfile, mimetypes
from dotenv import load_dotenv

# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 0. ๊ณตํ†ต ์ดˆ๊ธฐํ™” โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
    raise RuntimeError("OPENAI_API_KEY๋ฅผ .env ํŒŒ์ผ์— ์„ค์ •ํ•˜์„ธ์š”!")
client = openai.OpenAI(api_key=api_key)

LANGUAGES = [
    "Korean", "English", "Japanese", "Chinese",
    "Thai", "Russian", "Vietnamese",
    "Spanish", "French"
]
LANG_CODE = {
    "Korean":"ko","English":"en","Japanese":"ja","Chinese":"zh",
    "Thai":"th","Russian":"ru","Vietnamese":"vi",
    "Spanish":"es","French":"fr"
}
VOICE = {l: ("nova" if l in ["Korean","Japanese","Chinese"] else "alloy")
         for l in LANGUAGES}

FOUR_LANGS = ["English", "Chinese", "Thai", "Russian"]  # ์‹ค์‹œ๊ฐ„ ๋™์‹œ ๋ฒˆ์—ญ์šฉ
STREAM_SEC = 4  # Whisper ํ˜ธ์ถœ ๊ฐ„๊ฒฉ(์ดˆ) โ€“ 3~4 ์ดˆ ์ •๋„ ์ง€์—ฐ

# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 1. ์œ ํ‹ธ ํ•จ์ˆ˜ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def _safe_path(v):
    """Gradio File/Audio ์ž…๋ ฅ โ†’ ์‹ค์ œ ๊ฒฝ๋กœ ์ถ”์ถœ"""
    if v is None:
        return None
    return v.get("name") if isinstance(v, dict) else v

def _gpt_translate(text: str, src: str, tgt: str) -> str:
    """GPT-3.5-turbo ๋ฒˆ์—ญ (์„ค๋ช… ์—†์ด ๊ฒฐ๊ณผ๋งŒ)"""
    rsp = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role":"system",
             "content":f"You are a professional translator. Translate the following {src} text to {tgt}. "
                        f"Only provide the translated text."},
            {"role":"user","content":text}
        ],
        temperature=0.3,max_tokens=4096
    )
    return rsp.choices[0].message.content.strip()

def _tts(text: str, lang: str) -> str:
    """OpenAI TTS-1 โ‡’ MP3 ํŒŒ์ผ ๊ฒฝ๋กœ ๋ฐ˜ํ™˜"""
    out = client.audio.speech.create(
        model="tts-1",
        voice=VOICE.get(lang,"alloy"),
        input=text[:4096]
    )
    tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
    tmp.write(out.content)
    tmp.close()
    return tmp.name

# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 2. ๋‹จ๊ฑด ์˜ค๋””์˜ค ๋ฒˆ์—ญ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def translate_audio(audio_in, src, tgt):
    path = _safe_path(audio_in)
    if not path or not os.path.exists(path):
        return "โš ๏ธ ์Œ์„ฑ ํŒŒ์ผ์„ ๋…น์Œ-์—…๋กœ๋“œํ•˜์„ธ์š”.", "", None

    with open(path,"rb") as f:
        stt = client.audio.transcriptions.create(
            model="whisper-1",
            file=f,
            language=LANG_CODE.get(src)
        )
    original = stt.text.strip()
    if not original:
        return "โš ๏ธ ์Œ์„ฑ ์ธ์‹ ์‹คํŒจ", "", None

    translated = _gpt_translate(original, src, tgt)
    tts_path   = _tts(translated, tgt)
    return original, translated, tts_path

# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 3. PDF / ์ด๋ฏธ์ง€ ๋ฒˆ์—ญ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def translate_document(file_in, src, tgt):
    path = _safe_path(file_in)
    if not path or not os.path.exists(path):
        return "โš ๏ธ PDF(๋˜๋Š” ์ด๋ฏธ์ง€) ํŒŒ์ผ์„ ์—…๋กœ๋“œํ•˜์„ธ์š”.", ""

    ext  = os.path.splitext(path)[1].lower()
    mime = mimetypes.guess_type(path)[0] or ""
    text = ""

    try:
        if ext == ".pdf" or "pdf" in mime:
            import pdfplumber
            with pdfplumber.open(path) as pdf:
                pages = pdf.pages[:5]  # ๋ฐ๋ชจ: 5์ชฝ ์ œํ•œ
                text  = "\n".join(p.extract_text() or "" for p in pages)
        else:
            # ์ด๋ฏธ์ง€์˜ ๊ฒฝ์šฐ Tesseract ํ•„์š”
            try:
                from PIL import Image
                import pytesseract
                text = pytesseract.image_to_string(Image.open(path))
            except Exception:
                return "โš ๏ธ ์„œ๋ฒ„์— Tesseract OCR๊ฐ€ ์—†์–ด์„œ ์ด๋ฏธ์ง€ OCR์€ ์ง€์›๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. PDF๋งŒ ์‚ฌ์šฉํ•˜์„ธ์š”.", ""
    except Exception as e:
        return f"โŒ ํ…์ŠคํŠธ ์ถ”์ถœ ์‹คํŒจ: {e}", ""

    text = text.strip()
    if not text:
        return "โš ๏ธ ํ…์ŠคํŠธ๊ฐ€ ์ถ”์ถœ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.", ""

    translated = _gpt_translate(text, src, tgt)
    return text, translated

# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 4. ์‹ค์‹œ๊ฐ„ 1๊ฐœ ์–ธ์–ด ๋ฒˆ์—ญ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def stream_single(mic_stream, src, tgt):
    buf, header = io.BytesIO(), None
    o_acc, t_acc = "", ""
    while True:
        chunk = mic_stream.recv()
        if chunk is None:
            break
        if header is None:
            header = chunk[:44]
        buf.write(chunk)
        if buf.getbuffer().nbytes > 16000*2*STREAM_SEC:
            wav = header + buf.getvalue()
            with tempfile.NamedTemporaryFile(delete=False,suffix=".wav") as tmp:
                tmp.write(wav); tmp.close()
                o, t, _ = translate_audio(tmp.name, src, tgt)
            o_acc += " " + o
            t_acc += " " + t
            yield o_acc.strip(), t_acc.strip()
            buf = io.BytesIO()

    if buf.getbuffer().nbytes:
        wav = header + buf.getvalue()
        with tempfile.NamedTemporaryFile(delete=False,suffix=".wav") as tmp:
            tmp.write(wav); tmp.close()
            o, t, _ = translate_audio(tmp.name, src, tgt)
        yield (o_acc+" "+o).strip(), (t_acc+" "+t).strip()

# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 5. ์‹ค์‹œ๊ฐ„ 4๊ฐœ ์–ธ์–ด ๋ฒˆ์—ญ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def stream_multi(mic_stream, src):
    buf, header = io.BytesIO(), None
    acc = {lang:"" for lang in ["orig"]+FOUR_LANGS}

    while True:
        chunk = mic_stream.recv()
        if chunk is None:
            break
        if header is None:
            header = chunk[:44]
        buf.write(chunk)
        if buf.getbuffer().nbytes > 16000*2*STREAM_SEC:
            wav = header + buf.getvalue()
            with tempfile.NamedTemporaryFile(delete=False,suffix=".wav") as tmp:
                tmp.write(wav); tmp.close()
                with open(tmp.name,"rb") as f:
                    stt = client.audio.transcriptions.create(
                        model="whisper-1", file=f,
                        language=LANG_CODE.get(src)
                    )
            orig = stt.text.strip()
            if orig:
                acc["orig"] += " " + orig
                for lang in FOUR_LANGS:
                    acc[lang] += " " + _gpt_translate(orig, src, lang)
            yield (acc["orig"].strip(),
                   acc["English"].strip(),
                   acc["Chinese"].strip(),
                   acc["Thai"].strip(),
                   acc["Russian"].strip())
            buf = io.BytesIO()

    if buf.getbuffer().nbytes:
        wav = header + buf.getvalue()
        with tempfile.NamedTemporaryFile(delete=False,suffix=".wav") as tmp:
            tmp.write(wav); tmp.close()
            with open(tmp.name,"rb") as f:
                stt = client.audio.transcriptions.create(
                    model="whisper-1", file=f,
                    language=LANG_CODE.get(src)
                )
        orig = stt.text.strip()
        if orig:
            acc["orig"] += " " + orig
            for lang in FOUR_LANGS:
                acc[lang] += " " + _gpt_translate(orig, src, lang)
    yield (acc["orig"].strip(),
           acc["English"].strip(),
           acc["Chinese"].strip(),
           acc["Thai"].strip(),
           acc["Russian"].strip())

# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 6. Gradio UI โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
with gr.Blocks(title="SMARTok Demo", theme=gr.themes.Soft()) as app:
    with gr.Tabs():
        # ํƒญ 1 โ”€ ์˜ค๋””์˜ค ๋ฒˆ์—ญ
        with gr.TabItem("๐ŸŽ™๏ธ ์˜ค๋””์˜ค ๋ฒˆ์—ญ"):
            src1 = gr.Dropdown(LANGUAGES,value="Korean",label="์ž…๋ ฅ")
            tgt1 = gr.Dropdown(LANGUAGES,value="English",label="์ถœ๋ ฅ")
            aud1 = gr.Audio(sources=["microphone","upload"],
                            type="filepath",
                            label="๋…น์Œ ๋˜๋Š” ์˜ค๋””์˜ค ํŒŒ์ผ ์—…๋กœ๋“œ")
            btn1 = gr.Button("๋ฒˆ์—ญ")
            stt1 = gr.Textbox(label="์›๋ฌธ", lines=5)
            tlt1 = gr.Textbox(label="๋ฒˆ์—ญ", lines=5)
            out1 = gr.Audio(label="TTS",type="filepath",autoplay=True)
            btn1.click(translate_audio,[aud1,src1,tgt1],[stt1,tlt1,out1])

        # ํƒญ 2 โ”€ ๋ฌธ์„œ/์ด๋ฏธ์ง€ ๋ฒˆ์—ญ
        with gr.TabItem("๐Ÿ“„ ๋ฌธ์„œ/์ด๋ฏธ์ง€ ๋ฒˆ์—ญ"):
            src2 = gr.Dropdown(LANGUAGES,value="Korean",label="์ž…๋ ฅ")
            tgt2 = gr.Dropdown(LANGUAGES,value="English",label="์ถœ๋ ฅ")
            file2= gr.File(label="PDF ๋˜๋Š” ์ด๋ฏธ์ง€ ์—…๋กœ๋“œ",
                           file_types=[".pdf",".png",".jpg",".jpeg",".bmp",".tiff",".gif"])
            btn2 = gr.Button("๋ฒˆ์—ญ")
            org2 = gr.Textbox(label="์ถ”์ถœ ์›๋ฌธ",lines=15)
            trs2 = gr.Textbox(label="๋ฒˆ์—ญ ๊ฒฐ๊ณผ",lines=15)
            btn2.click(translate_document,[file2,src2,tgt2],[org2,trs2])

        # ํƒญ 3 โ”€ ์‹ค์‹œ๊ฐ„ 1์–ธ์–ด ๋ฒˆ์—ญ
        with gr.TabItem("โฑ๏ธ ์‹ค์‹œ๊ฐ„ 1์–ธ์–ด"):
            src3 = gr.Dropdown(LANGUAGES,value="Korean",label="์ž…๋ ฅ")
            tgt3 = gr.Dropdown(LANGUAGES,value="English",label="์ถœ๋ ฅ")
            mic3 = gr.Audio(sources=["microphone"],
                            streaming=True,
                            label="์‹ค์‹œ๊ฐ„ ๋งˆ์ดํฌ")
            stt3 = gr.Textbox(label="์›๋ฌธ(์‹ค์‹œ๊ฐ„)",lines=8)
            tlt3 = gr.Textbox(label="๋ฒˆ์—ญ(์‹ค์‹œ๊ฐ„)",lines=8)
            mic3.stream(stream_single,inputs=[src3,tgt3],outputs=[stt3,tlt3])

        # ํƒญ 4 โ”€ ์‹ค์‹œ๊ฐ„ 4๊ฐœ ์–ธ์–ด ๋ฒˆ์—ญ
        with gr.TabItem("๐ŸŒ ์‹ค์‹œ๊ฐ„ 4๊ฐœ ์–ธ์–ด"):
            gr.Markdown("๋งˆ์ดํฌ ์ž…๋ ฅ์„ 3-4 ์ดˆ ๊ฐ„๊ฒฉ์œผ๋กœ **English / Chinese(็ฎ€ไฝ“) / Thai / Russian** 4๊ฐœ ์–ธ์–ด๋กœ ๋™์‹œ ๋ฒˆ์—ญํ•ฉ๋‹ˆ๋‹ค.")
            src4 = gr.Dropdown(LANGUAGES,value="Korean",label="์ž…๋ ฅ ์–ธ์–ด")
            mic4 = gr.Audio(sources=["microphone"],
                            streaming=True,
                            label="์‹ค์‹œ๊ฐ„ ๋งˆ์ดํฌ")
            o4  = gr.Textbox(label="์›๋ฌธ",lines=8)
            e4  = gr.Textbox(label="English",lines=8)
            z4  = gr.Textbox(label="Chinese(็ฎ€ไฝ“)",lines=8)
            t4  = gr.Textbox(label="Thai",lines=8)
            r4  = gr.Textbox(label="Russian",lines=8)
            mic4.stream(stream_multi,inputs=[src4],
                        outputs=[o4,e4,z4,t4,r4])

# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 7. ์‹คํ–‰ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
if __name__ == "__main__":
    app.launch(server_name="0.0.0.0",
               server_port=7860,
               share=False,
               debug=True)