Browen0311 commited on
Commit
b2e13b5
·
verified ·
1 Parent(s): 65bb165

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -78
app.py CHANGED
@@ -2,12 +2,18 @@ import os
2
  from dotenv import load_dotenv
3
  import gradio as gr
4
  from openai import OpenAI
 
5
 
6
  # 載入環境變數
7
  load_dotenv()
8
  client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
9
 
10
- def grade_essay(essay_content, additional_prompt=""):
 
 
 
 
 
11
  criteria = {
12
  '題旨發揮': {'weight': 0.4, 'max_score': 40},
13
  '資料掌握': {'weight': 0.2, 'max_score': 20},
@@ -21,54 +27,29 @@ def grade_essay(essay_content, additional_prompt=""):
21
  'C+': 65, 'C': 60, 'C-': 55,
22
  '0': 0
23
  }
24
-
25
- def get_evaluation(prompt):
26
- response = client.chat.completions.create(
27
- model="gpt-3.5-turbo",
28
- messages=[
29
- {"role": "system", "content": "你是一位資深的國文作文評閱委員,請依據提供的評分規準進行評分。"},
30
- {"role": "user", "content": prompt}
31
- ],
32
- temperature=0.7
33
- )
34
- return response.choices[0].message.content
35
-
36
- def parse_response(response):
37
- lines = response.lower().split('\n')
38
- grade = '0'
39
- comment = ""
40
-
41
- for line in lines:
42
- if '等第:' in line or '等第:' in line:
43
- grade_text = line.split(':')[-1].strip().upper()
44
- if grade_text in grade_scores:
45
- grade = grade_text
46
- elif '評語:' in line or '評語:' in line:
47
- comment = line.split(':')[-1].strip()
48
-
49
- return grade, comment
50
-
51
  try:
52
  scores = {}
53
- feedback = {}
54
- result_text = []
55
 
56
- # 添加額外提示詞到作文內容
57
- if additional_prompt:
58
- evaluation_content = f"{essay_content}\n\n額外評分提示:{additional_prompt}"
59
- else:
60
- evaluation_content = essay_content
 
61
 
 
62
  for criterion, details in criteria.items():
63
  prompt = f"""評估以下作文的{criterion}(權重{details['weight']*100}%):
64
 
65
- 評分標準:
66
- A等(A+、A、A-):優秀表現
67
- B等(B+、B、B-):中等表現
68
- C等(C+、C、C-):待加強表現
69
-
70
  作文內容:
71
- {evaluation_content}
 
 
72
 
73
  請依三等九級制(A+、A、A-、B+、B、B-、C+、C、C-)評分,並提供簡短評語。
74
  如果是缺考、未作答、完全文不對題或作答內容完全照抄試題,請給予0分。
@@ -76,67 +57,102 @@ C等(C+、C、C-):待加強表現
76
  請按以下格式回覆:
77
  等第:
78
  評語:"""
 
 
 
 
 
 
 
 
 
79
 
80
- response = get_evaluation(prompt)
81
- grade, comment = parse_response(response)
 
 
82
 
83
- raw_score = grade_scores[grade]
84
- weighted_score = (raw_score / 100) * details['max_score']
 
 
 
 
 
85
 
86
- result_text.append(f"【{criterion}】")
87
- result_text.append(f"等第: {grade}")
88
- result_text.append(f"加權分數: {weighted_score:.1f}/{details['max_score']}")
89
- result_text.append(f"評語: {comment}")
90
- result_text.append("")
91
 
92
- scores[criterion] = weighted_score
 
 
 
93
 
94
- total_score = sum(scores.values())
95
- result_text.append(f"總分: {total_score:.1f}/100")
96
-
97
- return "\n".join(result_text)
 
 
98
 
99
  except Exception as e:
100
- return f"評分過程發生錯誤: {str(e)}"
 
 
 
 
 
 
101
 
102
- # 創建 Gradio 介面
103
  def create_interface():
104
  with gr.Blocks(title="國文作文自動評分系統") as iface:
105
  gr.Markdown("""
106
  # 國文作文自動評分系統
107
  ## 評分標準說明
108
- 本系統依據以下四個面向進行評分:
109
  - 題旨發揮 (40%)
110
  - 資料掌握 (20%)
111
  - 結構安排 (20%)
112
  - 字句運用 (20%)
113
 
114
- 採用三等九級制(A+、A、A-、B+、B、B-、C+、C、C-)進行評分。
115
  """)
116
 
117
- with gr.Column():
118
- essay_input = gr.Textbox(
119
- label="作文內容",
120
- placeholder="請在此輸入作文內容...",
121
- lines=10
122
- )
123
- prompt_input = gr.Textbox(
124
- label="額外評分提示(選填)",
125
- placeholder="可輸入額外的評分提示或要求...",
126
- lines=2
127
- )
128
- grade_button = gr.Button("開始評分", variant="primary")
129
- output = gr.Textbox(label="評分結果", lines=15)
 
 
 
 
 
 
 
 
 
 
 
 
130
 
131
- grade_button.click(
132
- fn=grade_essay,
133
- inputs=[essay_input, prompt_input],
134
- outputs=output
135
  )
136
-
 
137
  return iface
138
 
139
- # 啟動應用
140
  if __name__ == "__main__":
141
  demo = create_interface()
142
  demo.launch(share=True)
 
2
  from dotenv import load_dotenv
3
  import gradio as gr
4
  from openai import OpenAI
5
+ from datetime import datetime
6
 
7
  # 載入環境變數
8
  load_dotenv()
9
  client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
10
 
11
+ def evaluate_essay(message, history, additional_prompt):
12
+ if not message.strip():
13
+ return history + [
14
+ {"role": "assistant", "content": "請輸入作文內容進行評分。"}
15
+ ]
16
+
17
  criteria = {
18
  '題旨發揮': {'weight': 0.4, 'max_score': 40},
19
  '資料掌握': {'weight': 0.2, 'max_score': 20},
 
27
  'C+': 65, 'C': 60, 'C-': 55,
28
  '0': 0
29
  }
30
+
31
+ history.append({"role": "user", "content": f"要評分的作文內容:\n\n{message}"})
32
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  try:
34
  scores = {}
35
+ feedback = []
36
+ total_score = 0
37
 
38
+ # 評分前的提示訊息
39
+ history.append({
40
+ "role": "assistant",
41
+ "content": "正在進行評分分析...",
42
+ "metadata": {"title": "🔍 開始評分"}
43
+ })
44
 
45
+ # 評估每個面向
46
  for criterion, details in criteria.items():
47
  prompt = f"""評估以下作文的{criterion}(權重{details['weight']*100}%):
48
 
 
 
 
 
 
49
  作文內容:
50
+ {message}
51
+
52
+ {additional_prompt if additional_prompt else ''}
53
 
54
  請依三等九級制(A+、A、A-、B+、B、B-、C+、C、C-)評分,並提供簡短評語。
55
  如果是缺考、未作答、完全文不對題或作答內容完全照抄試題,請給予0分。
 
57
  請按以下格式回覆:
58
  等第:
59
  評語:"""
60
+
61
+ response = client.chat.completions.create(
62
+ model="gpt-3.5-turbo",
63
+ messages=[
64
+ {"role": "system", "content": "你是一位資深的國文作文評閱委員,請依據提供的評分規準進行評分。"},
65
+ {"role": "user", "content": prompt}
66
+ ],
67
+ temperature=0.7
68
+ )
69
 
70
+ result = response.choices[0].message.content
71
+ lines = result.lower().split('\n')
72
+ grade = '0'
73
+ comment = ""
74
 
75
+ for line in lines:
76
+ if '等第:' in line or '等第:' in line:
77
+ grade_text = line.split(':')[-1].strip().upper()
78
+ if grade_text in grade_scores:
79
+ grade = grade_text
80
+ elif '評語:' in line or '評語:' in line:
81
+ comment = line.split(':')[-1].strip()
82
 
83
+ weighted_score = (grade_scores[grade] / 100) * details['max_score']
84
+ total_score += weighted_score
 
 
 
85
 
86
+ feedback.append(f"**{criterion}** \n")
87
+ feedback.append(f"等第:{grade} \n")
88
+ feedback.append(f"得分:{weighted_score:.1f}/{details['max_score']} \n")
89
+ feedback.append(f"評語:{comment} \n\n")
90
 
91
+ # 添加評分結果
92
+ history.append({
93
+ "role": "assistant",
94
+ "content": "".join(feedback) + f"**總分:{total_score:.1f}/100**",
95
+ "metadata": {"title": "📝 評分結果"}
96
+ })
97
 
98
  except Exception as e:
99
+ history.append({
100
+ "role": "assistant",
101
+ "content": f"評分過程發生錯誤:{str(e)}",
102
+ "metadata": {"title": "❌ 錯誤"}
103
+ })
104
+
105
+ return history
106
 
 
107
  def create_interface():
108
  with gr.Blocks(title="國文作文自動評分系統") as iface:
109
  gr.Markdown("""
110
  # 國文作文自動評分系統
111
  ## 評分標準說明
112
+ 本系統採用以下四個面向進行評分:
113
  - 題旨發揮 (40%)
114
  - 資料掌握 (20%)
115
  - 結構安排 (20%)
116
  - 字句運用 (20%)
117
 
118
+ 評分採用三等九級制(A+、A、A-、B+、B、B-、C+、C、C-)
119
  """)
120
 
121
+ with gr.Row():
122
+ with gr.Column(scale=4):
123
+ chatbot = gr.Chatbot(
124
+ value=[],
125
+ height=500,
126
+ bubble_full_width=False,
127
+ avatar_images=("user.png", "assistant.png"),
128
+ show_copy_button=True,
129
+ layout="bubble",
130
+ render_markdown=True
131
+ )
132
+ msg = gr.Textbox(
133
+ label="請輸入作文內容",
134
+ placeholder="在此輸入作文...",
135
+ lines=3
136
+ )
137
+ additional_prompt = gr.Textbox(
138
+ label="額外評分提示(選填)",
139
+ placeholder="可輸入額外的評分要求或提示...",
140
+ lines=2
141
+ )
142
+
143
+ with gr.Row():
144
+ submit = gr.Button("開始評分", variant="primary")
145
+ clear = gr.Button("清除對話")
146
 
147
+ submit.click(
148
+ evaluate_essay,
149
+ inputs=[msg, chatbot, additional_prompt],
150
+ outputs=chatbot
151
  )
152
+ clear.click(lambda: [], outputs=chatbot)
153
+
154
  return iface
155
 
 
156
  if __name__ == "__main__":
157
  demo = create_interface()
158
  demo.launch(share=True)