dayuian commited on
Commit
2a9478d
·
verified ·
1 Parent(s): e7b5b55

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -76
app.py CHANGED
@@ -1,79 +1,58 @@
1
  import gradio as gr
2
- import json
3
- import random
4
- from transformers import AutoModelForCausalLM, AutoTokenizer
5
- import os
6
- import re
7
-
8
- # 模型初始化
9
- model_name = "EleutherAI/pythia-410m"
10
- tokenizer = AutoTokenizer.from_pretrained(model_name)
11
- model = AutoModelForCausalLM.from_pretrained(model_name)
12
-
13
- # 資料夾
14
- DATA_DIR = "./data"
15
-
16
- # 自動掃描資料夾生成選單
17
- def get_sources():
18
- files = os.listdir(DATA_DIR)
19
- sources = [f.split(".json")[0] for f in files if f.endswith(".json")]
20
- return sources
21
-
22
- # 清理 GPT 生成句子的雜訊
23
- def clean_sentence(output):
24
- output = re.sub(r"Write.*?beginners\.", "", output, flags=re.IGNORECASE).strip()
25
- output = re.sub(r"\*\*?\d+\.*\*\*", "", output).strip()
26
- if not output.endswith("."):
27
- output += "."
28
- return output
29
-
30
- # 核心函數
31
- def get_words_with_sentences(source, n):
32
- status = []
33
- try:
34
- data_path = os.path.join(DATA_DIR, f"{source}.json")
35
- with open(data_path, 'r', encoding='utf-8') as f:
36
- words = json.load(f)
37
-
38
- selected_words = random.sample(words, n)
39
- results = []
40
-
41
- for i, word_data in enumerate(selected_words):
42
- status.append(f"正在生成第 {i+1}/{n} 個單字 [{word_data['word']}] 例句...")
43
- word = word_data['word']
44
-
45
- prompt = f"Use the word '{word}' in a simple English sentence suitable for beginners. Output only the sentence."
46
-
47
- inputs = tokenizer(prompt, return_tensors="pt")
48
- outputs = model.generate(**inputs, max_new_tokens=30)
49
- sentence = tokenizer.decode(outputs[0], skip_special_tokens=True)
50
-
51
- clean_output = clean_sentence(sentence)
52
-
53
- results.append({
54
- "word": word,
55
- "phonetic": word_data["phonetic"],
56
- "sentence": clean_output
57
- })
58
-
59
- status.append("✅ 完成!")
60
- return results, status
61
-
62
- except Exception as e:
63
- status.append(f"❌ 發生錯誤: {str(e)}")
64
- return [], status
65
-
66
- # Gradio 介面
67
- demo = gr.Interface(
68
- fn=get_words_with_sentences,
69
- inputs=[
70
- gr.Dropdown(choices=get_sources(), value="common3000", label="選擇單字庫", interactive=True, show_clear_button=False),
71
- gr.Number(value=10, label="抽幾個單字")
72
- ],
73
- outputs=[
74
- gr.JSON(label="生成結果"),
75
- gr.JSON(label="生成進度")
76
- ]
77
- )
78
 
79
  demo.launch()
 
1
  import gradio as gr
2
+ from vocab import get_sources, get_words_with_sentences
3
+
4
+ with gr.Blocks() as demo:
5
+ gr.Markdown(
6
+ """
7
+ # 📖 英文單字隨機抽取 & GPT 例句生成 API
8
+
9
+ ## 📝 專案簡介
10
+ 本專案提供一個 API 服務,能夠從不同的單字庫隨機抽取單字,並使用開源語言模型自動生成例句。
11
+ 適合作為 LINE 單字推播、自學工具、英文教學輔助等用途。
12
+
13
+ ## ⚙️ 主要功能
14
+ - 支援從多個單字庫中選擇,如:`common3000`, `business_words`。
15
+ - 可自訂抽取單字數量。
16
+ - 每個單字自動生成一個簡單的英文例句,適合初學者學習。
17
+
18
+ ## 📚 使用方式
19
+ 1. 選擇單字庫(例如:`common3000`)。
20
+ 2. 設定抽取單字數量(例如:10個)。
21
+ 3. 點擊「生成例句」按鈕,即可獲得單字 + 音標 + 例句。
22
+
23
+ ## 🗂️ 資料來源
24
+ - **common3000**:常用3000單字表,附音標。
25
+ - 未來可能會有更多單字庫新增至 `/data/` 資料夾。(可能啦!
26
+
27
+ ## 🛠️ 技術架構
28
+ - **Gradio Blocks** 前端介面 + API。
29
+ - **Hugging Face Transformers** 語言模型:
30
+ - 模型:`EleutherAI/pythia-410m`(小型 GPT 模型)
31
+
32
+ ## 👨‍💻 開發者資訊
33
+ - 開發者:余彦志 (大宇 ian)
34
+ - 信箱:dayuian@hotmail.com
35
+ - GitHub:[https://github.com/dayuian](https://github.com/dayuian)
36
+ """
37
+ )
38
+
39
+ source_dropdown = gr.Dropdown(
40
+ choices=get_sources(),
41
+ value="common3000",
42
+ label="選擇單字庫",
43
+ interactive=True
44
+ )
45
+
46
+ num_input = gr.Number(value=10, label="抽幾個單字")
47
+ result_output = gr.HTML(label="生成結果")
48
+ status_output = gr.Textbox(label="狀態更新", lines=8, interactive=False)
49
+
50
+ submit_btn = gr.Button("生成例句")
51
+
52
+ submit_btn.click(
53
+ fn=get_words_with_sentences,
54
+ inputs=[source_dropdown, num_input],
55
+ outputs=[result_output, status_output]
56
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
  demo.launch()