DangoMachoo commited on
Commit
a4f2967
·
1 Parent(s): 6430135

update main

Browse files
Files changed (1) hide show
  1. app.py +61 -21
app.py CHANGED
@@ -4,6 +4,8 @@ from transformers import pipeline
4
  import os
5
  import tempfile
6
  import shutil
 
 
7
 
8
  # ✅ ตรวจสอบ ffmpeg
9
  if not shutil.which("ffmpeg"):
@@ -12,7 +14,7 @@ if not shutil.which("ffmpeg"):
12
  # ✅ ลบ path ffmpeg เฉพาะ local เพราะ Spaces มี ffmpeg ติดตั้งแล้ว
13
  # os.environ["PATH"] += os.pathsep + r"C:\ffmpeg\ffmpeg-master-latest-win64-gpl\ffmpeg-master-latest-win64-gpl\bin"
14
 
15
- # ✅ โหลดโมเดล
16
  MODEL_NAME = "biodatlab/whisper-th-small-combined"
17
  device = 0 if torch.cuda.is_available() else "cpu"
18
 
@@ -23,44 +25,78 @@ pipe = pipeline(
23
  device=device,
24
  )
25
 
26
- # ✅ ฟังก์ชันแปลงเสียงเป็นข้อความ และเซฟไฟล์
27
  def transcribe_audio(audio):
 
28
  if not audio:
29
- return "กรุณาอัปโหลดไฟล์เสียงก่อน", None
30
  try:
31
- result = pipe(audio, generate_kwargs={"language": "<|th|>", "task": "transcribe"}, batch_size=16)
32
  text = result["text"]
33
- with tempfile.NamedTemporaryFile(suffix=".txt", delete=False, mode="w", encoding="utf-8") as f:
34
- f.write(text)
35
- filepath = f.name
36
- return text, filepath
37
  except Exception as e:
38
- return f"เกิดข้อผิดพลาด: {str(e)}", None
39
 
40
- # ✅ ฟังก์ชันสำหรับดาวน์โหลด
41
- def get_download_filepath(filepath):
42
- if filepath and os.path.exists(filepath):
43
- return filepath
44
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  # ✅ UI Layout
47
- with gr.Blocks() as demo:
48
- gr.Markdown("## 🎤 แปลงเสียงพูดภาษาไทยเป็นข้อความ")
 
 
 
 
49
  with gr.Row():
50
  with gr.Column(scale=1):
51
  audio_input = gr.Audio(label="🎵 อัปโหลดไฟล์เสียง (MP3, WAV, M4A)", type="filepath")
 
 
 
 
 
52
  transcribe_btn = gr.Button("🔄 แปลงเสียงเป็นข้อความ")
53
  with gr.Column(scale=2):
54
- transcribed_text = gr.Textbox(label="📜 ข้อความที่แปลงแล้ว", lines=11)
 
55
  with gr.Row():
56
  copy_button = gr.Button("📋 คัดลอกข้อความ")
57
- download_button = gr.DownloadButton(label="⬇️ ดาวน์โหลด .txt")
58
 
59
  # Action
60
  transcribe_btn.click(
61
  fn=transcribe_audio,
62
  inputs=audio_input,
63
- outputs=[transcribed_text, download_button],
64
  show_progress=True
65
  )
66
 
@@ -73,7 +109,11 @@ with gr.Blocks() as demo:
73
  )
74
 
75
  # Action ดาวน์โหลด
76
- download_button.click(fn=get_download_filepath, inputs=download_button, outputs=download_button)
 
 
 
 
77
 
78
- # รันใน Hugging Face Spaces ด้วย auth
79
  demo.launch()
 
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"):
 
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
 
 
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
 
 
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()