PPloychor commited on
Commit
7ffbf27
·
verified ·
1 Parent(s): e8939bc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -15
app.py CHANGED
@@ -7,19 +7,18 @@ from transformers.pipelines.audio_utils import ffmpeg_read
7
  # -----------------------------
8
  # CONFIG
9
  # -----------------------------
10
- ASR_MODEL = "openai/whisper-large-v3" # เปลี่ยนรุ่นได้ตามต้องการ
11
  BATCH_SIZE = 8
12
  HAS_CUDA = torch.cuda.is_available()
13
  DEVICE = 0 if HAS_CUDA else "cpu"
14
  DTYPE = torch.float16 if HAS_CUDA else torch.float32
15
 
16
- # โหลดโมเดลครั้งเดียว
17
  asr_pipe = pipeline(
18
  task="automatic-speech-recognition",
19
  model=ASR_MODEL,
20
  device=DEVICE,
21
  torch_dtype=DTYPE,
22
- chunk_length_s=30, # ปลอดภัยสำหรับไฟล์ยาว
23
  )
24
 
25
  def _save_text_file(text: str, suffix: str = ".txt") -> str:
@@ -28,10 +27,34 @@ def _save_text_file(text: str, suffix: str = ".txt") -> str:
28
  f.write(text)
29
  return path
30
 
31
- def _transcribe_from_path(path: str, task: str):
32
- if not path:
33
- raise gr.Error("โปรดอัปโหลดไฟล์ก่อน")
34
- # อ่านเป็น bytes แล้วให้ ffmpeg แปลงเป็น waveform (mono float32)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  with open(path, "rb") as f:
36
  payload = f.read()
37
  audio = ffmpeg_read(payload, asr_pipe.feature_extractor.sampling_rate)
@@ -40,22 +63,21 @@ def _transcribe_from_path(path: str, task: str):
40
  out = asr_pipe(
41
  inputs,
42
  batch_size=BATCH_SIZE,
43
- generate_kwargs={"task": task}, # 'transcribe' = คงภาษาเดิม, 'translate' = แปลเป็นอังกฤษ
44
  return_timestamps=True,
45
  )
46
  text = out["text"]
47
  return text, _save_text_file(text, ".txt")
48
 
49
- # ---- entry points สำหรับ UI สามแท็บ ----
50
  def transcribe_mic(mic_path: str, task: str):
51
- return _transcribe_from_path(mic_path, task)
52
 
53
  def transcribe_audio(file_path: str, task: str):
54
- return _transcribe_from_path(file_path, task)
55
 
56
- def transcribe_video(video_path: str, task: str):
57
- # ffmpeg_read รองรับไฟล์วิดีโอได้ (จะดึงเสียงออกมาให้)
58
- return _transcribe_from_path(video_path, task)
59
 
60
  # -----------------------------
61
  # UI
@@ -78,7 +100,8 @@ with gr.Blocks(title="Whisper V3 – Transcriber (Audio + MP4)") as demo:
78
  gr.Button("Run").click(transcribe_audio, inputs=[up_audio, up_task], outputs=[up_text, up_file])
79
 
80
  with gr.Tab("🎬 Video MP4"):
81
- up_video = gr.Video(sources=["upload"], format="mp4", label="Upload MP4")
 
82
  vd_task = gr.Radio(["transcribe", "translate"], value="transcribe", label="Task")
83
  vd_text = gr.Textbox(label="Transcript", lines=10)
84
  vd_file = gr.File(label="Download Transcript (.txt)")
 
7
  # -----------------------------
8
  # CONFIG
9
  # -----------------------------
10
+ ASR_MODEL = "openai/whisper-large-v3"
11
  BATCH_SIZE = 8
12
  HAS_CUDA = torch.cuda.is_available()
13
  DEVICE = 0 if HAS_CUDA else "cpu"
14
  DTYPE = torch.float16 if HAS_CUDA else torch.float32
15
 
 
16
  asr_pipe = pipeline(
17
  task="automatic-speech-recognition",
18
  model=ASR_MODEL,
19
  device=DEVICE,
20
  torch_dtype=DTYPE,
21
+ chunk_length_s=30,
22
  )
23
 
24
  def _save_text_file(text: str, suffix: str = ".txt") -> str:
 
27
  f.write(text)
28
  return path
29
 
30
+ def _resolve_path(x):
31
+ """
32
+ รับค่า input ได้ทั้ง:
33
+ - str (filepath)
34
+ - dict ที่มี key 'name' หรือ 'path'
35
+ - gradio FileData (มี .path)
36
+ คืนค่าเป็น filepath เสมอ
37
+ """
38
+ if x is None:
39
+ return None
40
+ if isinstance(x, str):
41
+ return x
42
+ # Gradio v4/v5 บางทีให้เป็น dict
43
+ if isinstance(x, dict):
44
+ return x.get("path") or x.get("name")
45
+ # Gradio FileData
46
+ path = getattr(x, "path", None)
47
+ if path:
48
+ return path
49
+ # เผื่อกรณี edge
50
+ return str(x)
51
+
52
+ def _transcribe_from_any(file_like, task: str):
53
+ path = _resolve_path(file_like)
54
+ if not path or not os.path.exists(path):
55
+ raise gr.Error("ไม่พบไฟล์ที่อัปโหลด (path ว่างหรือไฟล์หาย)")
56
+
57
+ # อ่านเป็น bytes แล้วให้ ffmpeg แปลงเป็นโมโน float32
58
  with open(path, "rb") as f:
59
  payload = f.read()
60
  audio = ffmpeg_read(payload, asr_pipe.feature_extractor.sampling_rate)
 
63
  out = asr_pipe(
64
  inputs,
65
  batch_size=BATCH_SIZE,
66
+ generate_kwargs={"task": task}, # 'transcribe' = ตามภาษาเดิม, 'translate' = แปลอังกฤษ
67
  return_timestamps=True,
68
  )
69
  text = out["text"]
70
  return text, _save_text_file(text, ".txt")
71
 
 
72
  def transcribe_mic(mic_path: str, task: str):
73
+ return _transcribe_from_any(mic_path, task)
74
 
75
  def transcribe_audio(file_path: str, task: str):
76
+ return _transcribe_from_any(file_path, task)
77
 
78
+ def transcribe_video(video_file, task: str):
79
+ # รับเป็นไฟล์วิดีโอ (mp4, mov, webm ก็ได้) แล้วให้ ffmpeg_read ดึงเสียง
80
+ return _transcribe_from_any(video_file, task)
81
 
82
  # -----------------------------
83
  # UI
 
100
  gr.Button("Run").click(transcribe_audio, inputs=[up_audio, up_task], outputs=[up_text, up_file])
101
 
102
  with gr.Tab("🎬 Video MP4"):
103
+ # ใช้ gr.File เพื่อให้ได้ path ที่นิ่งที่สุด
104
+ up_video = gr.File(file_count="single", file_types=["video"], label="Upload MP4 / Video")
105
  vd_task = gr.Radio(["transcribe", "translate"], value="transcribe", label="Task")
106
  vd_text = gr.Textbox(label="Transcript", lines=10)
107
  vd_file = gr.File(label="Download Transcript (.txt)")