NamVo commited on
Commit
eaca910
·
verified ·
1 Parent(s): 76ebaa0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +124 -124
app.py CHANGED
@@ -1,124 +1,124 @@
1
- import gradio as gr
2
- import numpy as np
3
- import scipy.io.wavfile as wavfile
4
- import soundfile as sf
5
- import time
6
- import uuid
7
- import os
8
- import csv
9
- from supabase import create_client
10
-
11
- # Supabase
12
- url = "https://eecucubpmvpjkhqletul.supabase.co"
13
- key = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImVlY3VjdWJwbXZwamtocWxldHVsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDQ3MTc5MzUsImV4cCI6MjA2MDI5MzkzNX0.Av-ZEQ2xczudhm2c8p1JioXRXQCf4s0m4X_w5jrkf-8" # Cẩn thận không chia sẻ publicly!
14
- DB = create_client(supabase_url=url, supabase_key=key)
15
-
16
-
17
- def local_storage_set(key, value):
18
- value = json.dumps(value, ensure_ascii=False) # Convert to JSON string
19
- st_javascript(f"localStorage.setItem('{key}', {value});")
20
-
21
-
22
- # Function to get a value from localStorage
23
- def local_storage_get(key):
24
- return st_javascript(f"localStorage.getItem('{key}');")
25
-
26
-
27
- def get_transcripts(path: str):
28
- samples = []
29
- with open(path, newline='', encoding='utf-8') as csvfile:
30
- reader = csv.reader(csvfile)
31
- next(reader)
32
- for row in reader:
33
- samples.append(f"{row[0]} - {row[1]}")
34
- return samples
35
-
36
-
37
- def get_provinces(path):
38
- provinces = []
39
- with open(path, newline='', encoding='utf-8') as csvfile:
40
- reader = csv.reader(csvfile)
41
- next(reader)
42
- for row in reader:
43
- provinces.append(f"{row[0]}")
44
- return provinces
45
-
46
-
47
- def save_data(audio, transcript, age, gender, region):
48
- if age < 1:
49
- return "⚠️ Bạn cần nhập đúng số tuổi."
50
-
51
- if not transcript or not gender or not region.strip():
52
- return "⚠️ Bạn cần nhập đầy đủ các thông tin: Câu thoại, Giới tính và Tỉnh/TP."
53
-
54
- if audio is None:
55
- return "⚠️ Vui lòng ghi âm trước khi lưu."
56
-
57
- session_id = str(uuid.uuid4())
58
- audio_array = np.frombuffer(audio[-1], dtype=np.int16)
59
- filename = f"upload/recorded_audio_{int(time.time())}.wav"
60
- wavfile.write(filename, 44100, audio_array)
61
-
62
- DB.storage.from_("cs-bucket").upload(file=filename, path=f"{filename}", file_options={"content-type": "audio/wav"})
63
- url = DB.storage.from_("cs-bucket").get_public_url(path=f"{filename}")
64
-
65
- word = transcript.split("-")[0]
66
- transcript_text = transcript.split("-")[1]
67
-
68
- DB.table("cs-data").insert({
69
- "user_id": session_id,
70
- "audio_url": url,
71
- "word": word,
72
- "transcript_text": transcript_text,
73
- "age": age,
74
- "gender": gender,
75
- "region": region.strip()
76
- }).execute()
77
-
78
- if os.path.exists(filename):
79
- os.remove(filename)
80
-
81
- return "✅ Dữ liệu đã được lưu thành công. Cảm ơn bạn!"
82
-
83
-
84
- transcripts = get_transcripts("scripts.csv")
85
- provinces = get_provinces("vietnam_provinces.csv")
86
-
87
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
88
- gr.Markdown("""
89
- <h1 style="
90
- font-size: 32px;
91
- text-align: center;
92
- ">
93
- 🎤 Ứng dụng ghi âm và thu thập dữ liệu
94
- </h1>
95
- """)
96
-
97
- with gr.Row():
98
- with gr.Column(scale=3):
99
- transcript = gr.Dropdown(label="Chọn câu thoại", choices=transcripts)
100
- age = gr.Number(label="Tuổi")
101
- gender = gr.Dropdown(label="Giới tính", choices=["Nam", "Nữ"])
102
- region = gr.Dropdown(label="Tỉnh/TP", choices=provinces)
103
- audio = gr.Audio(sources="microphone", type="numpy", label="Ghi âm tại đây")
104
- submit_btn = gr.Button("Lưu dữ liệu")
105
- output = gr.Textbox(label="Thông báo")
106
- submit_btn.click(save_data, inputs=[audio, transcript, age, gender, region], outputs=output)
107
-
108
- with gr.Column(scale=2):
109
- gr.Markdown("<h3 style='font-size: 22px'>📌 Hướng dẫn sử dụng</h3>")
110
- gr.Markdown("""
111
- <div style="font-size: 18px">
112
- <b>Bước 1:</b> Chọn đoạn thoại bạn muốn ghi âm trong hộp gợi ý.<br>
113
- <b>Bước 2:</b> Điền đầy đủ thông tin (<i>tuổi, giới tính, tỉnh/thành</i>).<br>
114
- <b>Bước 3:</b> Bấm <b>Start Recording</b> để ghi âm, sau đó bấm <b>Stop</b> và nghe lại.<br>
115
- <b>Bước 4:</b> Nếu ghi âm bị lỗi hoặc thiếu, bấm <b>Reset</b> để ghi lại.<br>
116
- <b>Bước 5:</b> Bấm <b>“Lưu dữ liệu”</b> để gửi ghi âm về cho nhóm phát triển.<br><br>
117
-
118
- <span style="color: red">🔊 Lưu ý:</span> Bạn có thể phát âm từ tiếng Anh theo kiểu Việt hóa.<br>
119
- Ví dụ: <code>ability</code> → <i>ờ bi li ti</i><br><br>
120
- 👉 Hãy cố gắng giúp ghi âm <b>5 câu</b> nếu có thể nhé! Cảm ơn sự giúp đỡ của bạn
121
- </div>
122
- """)
123
-
124
- demo.launch(share=True, mcp_server=False)
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import scipy.io.wavfile as wavfile
4
+ import soundfile as sf
5
+ import time
6
+ import uuid
7
+ import os
8
+ import csv
9
+ from supabase import create_client
10
+
11
+ # Supabase
12
+ url = "https://eecucubpmvpjkhqletul.supabase.co"
13
+ key = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImVlY3VjdWJwbXZwamtocWxldHVsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDQ3MTc5MzUsImV4cCI6MjA2MDI5MzkzNX0.Av-ZEQ2xczudhm2c8p1JioXRXQCf4s0m4X_w5jrkf-8" # Cẩn thận không chia sẻ publicly!
14
+ DB = create_client(supabase_url=url, supabase_key=key)
15
+
16
+
17
+ def local_storage_set(key, value):
18
+ value = json.dumps(value, ensure_ascii=False) # Convert to JSON string
19
+ st_javascript(f"localStorage.setItem('{key}', {value});")
20
+
21
+
22
+ # Function to get a value from localStorage
23
+ def local_storage_get(key):
24
+ return st_javascript(f"localStorage.getItem('{key}');")
25
+
26
+
27
+ def get_transcripts(path: str):
28
+ samples = []
29
+ with open(path, newline='', encoding='utf-8') as csvfile:
30
+ reader = csv.reader(csvfile)
31
+ next(reader)
32
+ for row in reader:
33
+ samples.append(f"{row[0]} - {row[1]}")
34
+ return samples
35
+
36
+
37
+ def get_provinces(path):
38
+ provinces = []
39
+ with open(path, newline='', encoding='utf-8') as csvfile:
40
+ reader = csv.reader(csvfile)
41
+ next(reader)
42
+ for row in reader:
43
+ provinces.append(f"{row[0]}")
44
+ return provinces
45
+
46
+
47
+ def save_data(audio, transcript, age, gender, region):
48
+ if age < 1:
49
+ return "⚠️ Bạn cần nhập đúng số tuổi."
50
+
51
+ if not transcript or not gender or not region.strip():
52
+ return "⚠️ Bạn cần nhập đầy đủ các thông tin: Câu thoại, Giới tính và Tỉnh/TP."
53
+
54
+ if audio is None:
55
+ return "⚠️ Vui lòng ghi âm trước khi lưu."
56
+
57
+ session_id = str(uuid.uuid4())
58
+ audio_array = np.frombuffer(audio[-1], dtype=np.int16)
59
+ filename = f"upload/recorded_audio_{int(time.time())}.wav"
60
+ wavfile.write(filename, 44100, audio_array)
61
+
62
+ DB.storage.from_("cs-bucket").upload(file=filename, path=f"{filename}", file_options={"content-type": "audio/wav"})
63
+ url = DB.storage.from_("cs-bucket").get_public_url(path=f"{filename}")
64
+
65
+ word = transcript.split("-")[0]
66
+ transcript_text = transcript.split("-")[1]
67
+
68
+ DB.table("cs-data").insert({
69
+ "user_id": session_id,
70
+ "audio_url": url,
71
+ "word": word,
72
+ "transcript_text": transcript_text,
73
+ "age": age,
74
+ "gender": gender,
75
+ "region": region.strip()
76
+ }).execute()
77
+
78
+ if os.path.exists(filename):
79
+ os.remove(filename)
80
+
81
+ return "✅ Dữ liệu đã được lưu thành công. Cảm ơn bạn!"
82
+
83
+
84
+ transcripts = get_transcripts("scripts.csv")
85
+ provinces = get_provinces("vietnam_provinces.csv")
86
+
87
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
88
+ gr.Markdown("""
89
+ <h1 style="
90
+ font-size: 32px;
91
+ text-align: center;
92
+ ">
93
+ 🎤 Ứng dụng ghi âm và thu thập dữ liệu
94
+ </h1>
95
+ """)
96
+
97
+ with gr.Row():
98
+ with gr.Column(scale=3):
99
+ transcript = gr.Dropdown(label="Chọn câu thoại", choices=transcripts)
100
+ age = gr.Number(label="Tuổi")
101
+ gender = gr.Dropdown(label="Giới tính", choices=["Nam", "Nữ"])
102
+ region = gr.Dropdown(label="Tỉnh/TP", choices=provinces)
103
+ audio = gr.Audio(sources="microphone", type="numpy", label="Ghi âm tại đây")
104
+ submit_btn = gr.Button("Lưu dữ liệu")
105
+ output = gr.Textbox(label="Thông báo")
106
+ submit_btn.click(save_data, inputs=[audio, transcript, age, gender, region], outputs=output)
107
+
108
+ with gr.Column(scale=2):
109
+ gr.Markdown("<h3 style='font-size: 22px'>📌 Hướng dẫn sử dụng</h3>")
110
+ gr.Markdown("""
111
+ <div style="font-size: 18px">
112
+ <b>Bước 1:</b> Chọn đoạn thoại bạn muốn ghi âm trong hộp gợi ý.<br>
113
+ <b>Bước 2:</b> Điền đầy đủ thông tin (<i>tuổi, giới tính, tỉnh/thành</i>).<br>
114
+ <b>Bước 3:</b> Bấm <b>Start Recording</b> để ghi âm, sau đó bấm <b>Stop</b> và nghe lại.<br>
115
+ <b>Bước 4:</b> Nếu ghi âm bị lỗi hoặc thiếu, bấm <b>Reset</b> để ghi lại.<br>
116
+ <b>Bước 5:</b> Bấm <b>“Lưu dữ liệu”</b> để gửi ghi âm về cho nhóm phát triển.<br><br>
117
+
118
+ <span style="color: red">🔊 Lưu ý:</span> Bạn có thể phát âm từ tiếng Anh theo kiểu Việt hóa.<br>
119
+ Ví dụ: <code>ability</code> → <i>ờ bi li ti</i><br><br>
120
+ 👉 Hãy cố gắng giúp ghi âm <b>5 câu</b> nếu có thể nhé! Cảm ơn sự giúp đỡ của bạn
121
+ </div>
122
+ """)
123
+
124
+ demo.launch()