DangoMachoo commited on
Commit
f89e973
·
1 Parent(s): 216427b

latest ver

Browse files
Files changed (1) hide show
  1. app.py +93 -22
app.py CHANGED
@@ -2,13 +2,20 @@ import gradio as gr
2
  import torch
3
  from transformers import pipeline
4
  import os
 
 
 
 
5
 
6
- # ✅ ใช้ path ffmpeg ชั่วคราวเฉพาะใน local
7
- #os.environ["PATH"] += os.pathsep + r"C:\ffmpeg\ffmpeg-master-latest-win64-gpl\ffmpeg-master-latest-win64-gpl\bin"
 
8
 
9
- # ✅ โมเดลที่ใช้
 
 
 
10
  MODEL_NAME = "biodatlab/whisper-th-small-combined"
11
- lang = "th"
12
  device = 0 if torch.cuda.is_available() else "cpu"
13
 
14
  pipe = pipeline(
@@ -18,31 +25,95 @@ pipe = pipeline(
18
  device=device,
19
  )
20
 
21
- # ✅ ฟังก์ชันแปลงเสียงเป็นข้อความ
22
  def transcribe_audio(audio):
23
- result = pipe(audio, generate_kwargs={"language": "<|th|>", "task": "transcribe"}, batch_size=16)
24
- text = result["text"]
25
- return text, text # ส่งทั้งแสดงบนหน้าจอ และโหลดเป็น .txt
 
 
 
 
 
 
 
 
26
 
27
- # ✅ UI ด้วย Gradio
28
- with gr.Blocks() as demo:
29
- gr.Markdown("## 🎤 แปลงเสียงพูดภาษาไทยเป็นข้อความ")
30
- with gr.Row():
31
- audio_input = gr.Audio(label="อัปโหลดไฟล์เสียง (MP3)", type="filepath")
32
- with gr.Row():
33
- transcribed_text = gr.Textbox(label="📜 ข้อความที่แปลงแล้ว", lines=10)
34
- with gr.Row():
35
- copy_button = gr.Button("📋 Copy")
36
- download_button = gr.File(label="⬇️ ดาวน์โหลด .txt")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
- # ปุ่มเริ่มแปลง
39
- transcribe_btn = gr.Button("🔄 แปลงเสียงเป็นข้อความ")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
- # เมื่อกดปุ่ม
42
  transcribe_btn.click(
43
  fn=transcribe_audio,
44
  inputs=audio_input,
45
- outputs=[transcribed_text, download_button]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  )
47
 
 
48
  demo.launch()
 
2
  import torch
3
  from transformers import pipeline
4
  import os
5
+ import tempfile
6
+ import shutil
7
+ from docx import Document
8
+ import time
9
 
10
+ # ✅ ตรวจสอบ ffmpeg
11
+ if not shutil.which("ffmpeg"):
12
+ raise EnvironmentError("ffmpeg not found. Please install ffmpeg and ensure it's in PATH.")
13
 
14
+ # ✅ ลบ path ffmpeg เฉพาะ local เพราะ Spaces มี ffmpeg ติดตั้งแล้ว
15
+ # os.environ["PATH"] += os.pathsep + r"C:\ffmpeg\ffmpeg-master-latest-win64-gpl\ffmpeg-master-latest-win64-gpl\bin"
16
+
17
+ # ✅ โหลดโมเดล small
18
  MODEL_NAME = "biodatlab/whisper-th-small-combined"
 
19
  device = 0 if torch.cuda.is_available() else "cpu"
20
 
21
  pipe = pipeline(
 
25
  device=device,
26
  )
27
 
28
+ # ✅ ฟังก์ชันแปลงเสียงเป็นข้อความ (return text และ processing time)
29
  def transcribe_audio(audio):
30
+ start_time = time.time() # บันทึกเวลาเริ่มต้น
31
+ if not audio:
32
+ return "กรุณาอัปโหลดไฟล์เสียงก่อน", "ไม่ได้ประมวลผล"
33
+ try:
34
+ result = pipe(audio, generate_kwargs={"language": "<|th|>", "task": "transcribe"}, batch_size=14)
35
+ text = result["text"]
36
+ end_time = time.time() # บันทึกเวลาสิ้นสุด
37
+ processing_time = end_time - start_time
38
+ return text, f"ใช้เวลา: {processing_time:.2f} วินาที"
39
+ except Exception as e:
40
+ return f"เกิดข้อผิดพลาด: {str(e)}", "เกิดข้อผิดพลาด"
41
 
42
+ # ✅ ฟังก์ชันสร้างไฟล์สำหรับดาวน์โหลด (.txt หรือ .docx)
43
+ def create_download_file(text, file_format):
44
+ if not text or text.startswith("กรุณา") or text.startswith("เกิดข้อผิดพลาด"):
45
+ return None
46
+ try:
47
+ if file_format == "Text (.txt)":
48
+ with tempfile.NamedTemporaryFile(suffix=".txt", delete=False, mode="w", encoding="utf-8") as f:
49
+ f.write(text)
50
+ return f.name
51
+ else: # Word (.docx)
52
+ doc = Document()
53
+ doc.add_paragraph(text)
54
+ with tempfile.NamedTemporaryFile(suffix=".docx", delete=False) as f:
55
+ doc.save(f.name)
56
+ return f.name
57
+ except Exception as e:
58
+ return None
59
+
60
+ # ✅ CSS สำหรับจัด Markdown ตรงกลางและทำให้ Textbox มีแถบเลื่อน
61
+ custom_css = """
62
+ .markdown {
63
+ text-align: center !important;
64
+ }
65
+ #transcribed-text textarea {
66
+ height: 250px !important;
67
+ overflow-y: auto !important;
68
+ resize: vertical !important;
69
+ }
70
+ """
71
 
72
+ # ✅ UI Layout
73
+ with gr.Blocks(css=custom_css) as demo:
74
+ gr.Markdown("""
75
+ <div style="text-align: center;">
76
+ <h2> แปลงเสียงพูดภาษาไทยเป็นข้อความ </h2>
77
+ </div>
78
+ """)
79
+ with gr.Row():
80
+ with gr.Column(scale=1):
81
+ audio_input = gr.Audio(label="🎵 อัปโหลดไฟล์เสียง (MP3, WAV, M4A)", type="filepath")
82
+ download_format = gr.Dropdown(
83
+ choices=["Text (.txt)", "Word (.docx)"],
84
+ label="📄 เลือกฟอร์แมตไฟล์",
85
+ value="Text (.txt)"
86
+ )
87
+ transcribe_btn = gr.Button("🔄 แปลงเสียงเป็นข้อความ")
88
+ with gr.Column(scale=2):
89
+ transcribed_text = gr.Textbox(label="📜 ข้อความที่แปลงแล้ว", elem_id="transcribed-text")
90
+ processing_time_display = gr.Textbox(label="⏱️ เวลาที่ใช้", interactive=False)
91
+ with gr.Row():
92
+ copy_button = gr.Button("📋 คัดลอกข้อความ")
93
+ download_button = gr.DownloadButton(label="⬇️ ดาวน์โหลดไฟล์")
94
 
95
+ # Action
96
  transcribe_btn.click(
97
  fn=transcribe_audio,
98
  inputs=audio_input,
99
+ outputs=[transcribed_text, processing_time_display],
100
+ show_progress=True
101
+ )
102
+
103
+ # Action คัดลอก (ใช้ JavaScript)
104
+ copy_button.click(
105
+ fn=None,
106
+ inputs=transcribed_text,
107
+ outputs=None,
108
+ js="function(text) {navigator.clipboard.writeText(text); gr.Info('คัดลอกข้อความแล้ว!'); return []}"
109
+ )
110
+
111
+ # Action ดาวน์โหลด
112
+ download_button.click(
113
+ fn=create_download_file,
114
+ inputs=[transcribed_text, download_format],
115
+ outputs=download_button
116
  )
117
 
118
+ # รันใน Hugging Face Spaces
119
  demo.launch()