Spaces:
Sleeping
Sleeping
File size: 10,006 Bytes
206b732 73b9bb5 206b732 73b9bb5 53e2dbe 34c33dc 73b9bb5 53e2dbe 73b9bb5 34c33dc 73b9bb5 e5cd568 53e2dbe e5cd568 53e2dbe e5cd568 53e2dbe e5cd568 53e2dbe e5cd568 53e2dbe e5cd568 206b732 73b9bb5 53e2dbe e360323 53e2dbe e360323 34c33dc 73b9bb5 34ccda0 53e2dbe 34ccda0 823109c 53e2dbe 823109c 73b9bb5 34ccda0 73b9bb5 0c39a47 34c33dc 0c39a47 53e2dbe e360323 0c39a47 53e2dbe 0c39a47 53e2dbe |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 |
import os
import gradio as gr
from openai import OpenAI
# 安裝並導入 Groq
try:
from groq import Groq
except ImportError:
os.system('pip install groq')
from groq import Groq
# 初始化 API clients
openai_client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
groq_client = Groq(api_key=os.getenv('groq_key'))
# 更新後的模型設定,包含最新的模型
OPENAI_MODELS = [
# GPT-4o 系列
"gpt-4o", # 最新的旗艦模型
"gpt-4o-2024-08-06", # 支援結構化輸出的版本
"gpt-4o-mini", # 輕量快速版本
"chatgpt-4o-latest", # ChatGPT使用的持續更新版本
# GPT-4 Turbo 系列
"gpt-4-turbo", # 最新的GPT-4 Turbo
"gpt-3.5-turbo", # GPT-3.5 Turbo
]
GROQ_MODELS = ["llama3-8b-8192", "gemma2-9b-it"]
MODEL_CONFIGS = {
"openai": {
# GPT-4o 系列配置
"gpt-4o": {
"max_tokens": 16384,
"temperature": 0.7,
"context_window": 128000
},
"gpt-4o-2024-08-06": {
"max_tokens": 16384,
"temperature": 0.7,
"context_window": 128000
},
"gpt-4o-mini": {
"max_tokens": 16384,
"temperature": 0.7,
"context_window": 128000
},
"chatgpt-4o-latest": {
"max_tokens": 16384,
"temperature": 0.7,
"context_window": 128000
},
# GPT-4 Turbo 系列配置
"gpt-4-turbo": {
"max_tokens": 4096,
"temperature": 0.7,
"context_window": 128000
},
"gpt-3.5-turbo": {
"max_tokens": 4096,
"temperature": 0.7,
"context_window": 16385
}
},
"groq": {
"llama3-8b-8192": {"max_tokens": 4090, "temperature": 0.7},
"gemma2-9b-it": {"max_tokens": 1024, "temperature": 0.7}
}
}
def get_llm_response(prompt, provider, model):
"""獲取LLM回應的函數"""
try:
if provider == "openai":
response = openai_client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": """你是一位資深的國文作文評閱委員,請依據以下評分規準進行評分:
1. 題旨發揮 (40%): 檢視作文是否切合題目要求、思路清晰、感發得宜、體悟深刻
2. 資料掌握 (20%): 評估材料運用是否恰當、例證是否充實
3. 結構安排 (20%): 審視文章結構是否完整、條理是否分明
4. 字句運用 (20%): 考察遣詞造句是否精確、修辭是否優美
請依三等九級制(A+、A、A-、B+、B、B-、C+、C、C-)評分。
若有缺考、未作答、完全文不對題或作答內容完全照抄試題者,則給予0分。
"""},
{"role": "user", "content": prompt}
],
temperature=MODEL_CONFIGS["openai"][model]["temperature"],
max_tokens=MODEL_CONFIGS["openai"][model]["max_tokens"]
)
return response.choices[0].message.content
else: # groq
completion = groq_client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": "你是一位資深的國文作文評閱委員,請依據提供的評分規準進行評分。"},
{"role": "user", "content": prompt}
],
**MODEL_CONFIGS["groq"][model],
stream=False,
top_p=1,
stop=None
)
return completion.choices[0].message.content
except Exception as e:
return f"評分過程發生錯誤:{str(e)}"
def evaluate_essay(message, additional_prompt, provider, model):
"""評估作文的主函數"""
if not message.strip():
return [], gr.Markdown("### 請輸入作文內容進行評分")
criteria = {
'題旨發揮': {'weight': 0.4, 'max_score': 40},
'資料掌握': {'weight': 0.2, 'max_score': 20},
'結構安排': {'weight': 0.2, 'max_score': 20},
'字句運用': {'weight': 0.2, 'max_score': 20}
}
grade_scores = {
'A+': 95, 'A': 90, 'A-': 85,
'B+': 80, 'B': 75, 'B-': 70,
'C+': 65, 'C': 60, 'C-': 55,
'0': 0
}
try:
history = []
total_score = 0
history.append(("作文內容:", message))
history.append(("", f"正在使用 {provider} ({model}) 進行評分分析..."))
all_feedback = {}
for criterion, details in criteria.items():
prompt = f"""評估以下作文的{criterion}(權重{details['weight']*100}%):
作文內容:
{message}
{additional_prompt if additional_prompt else ''}
請依三等九級制(A+、A、A-、B+、B、B-、C+、C、C-)評分,並提供詳細評語。
如果是缺考、未作答、完全文不對題或作答內容完全照抄試題,請給予0分。
請按以下格式回覆:
等第:
評語:"""
result = get_llm_response(prompt, provider, model)
lines = result.lower().split('\n')
grade = '0'
comment = ""
for line in lines:
if '等第:' in line or '等第:' in line:
grade_text = line.split(':')[-1].strip().upper()
if grade_text in grade_scores:
grade = grade_text
elif '評語:' in line or '評語:' in line:
comment = line.split(':')[-1].strip()
weighted_score = (grade_scores[grade] / 100) * details['max_score']
total_score += weighted_score
feedback = f"### {criterion}\n"
feedback += f"- **等第**:{grade}\n"
feedback += f"- **得分**:{weighted_score:.1f}/{details['max_score']}\n"
feedback += f"- **評語**:{comment}\n"
all_feedback[criterion] = feedback
# 添加各項評分到歷史記錄
for criterion in criteria:
history.append(("", all_feedback[criterion]))
# 生成總評
total_evaluation = """
### 綜合評語
本作文各項得分如下:
"""
for criterion, details in criteria.items():
total_evaluation += f"- {criterion}:{all_feedback[criterion].split('得分**:')[1].split('/')[0]}/{details['max_score']}\n"
total_evaluation += f"\n### 總分:{total_score:.1f}/100"
history.append(("", total_evaluation))
total_score_display = f"""
# 總評分結果
## 使用模型:{provider} ({model})
## 總分:{total_score:.1f}/100
"""
return history, gr.Markdown(total_score_display)
except Exception as e:
return [("", f"評分過程發生錯誤:{str(e)}")], gr.Markdown("### ❌ 評分失敗")
def update_model_choices(provider):
"""更新模型選擇的函數"""
if provider == "openai":
return gr.Dropdown(choices=OPENAI_MODELS, value="gpt-4o")
else:
return gr.Dropdown(choices=GROQ_MODELS, value="llama3-8b-8192")
# 建立 Gradio 介面
with gr.Blocks(title="國文作文自動評分系統") as demo:
gr.Markdown("""
# 國文作文自動評分系統
## 評分標準說明
本系統採用以下四個面向進行評分:
- 題旨發揮 (40%): 檢視作文是否切合題目要求、思路清晰、感發得宜、體悟深刻
- 資料掌握 (20%): 評估材料運用是否恰當、例證是否充實
- 結構安排 (20%): 審視文章結構是否完整、條理是否分明
- 字句運用 (20%): 考察遣詞造句是否精確、修辭是否優美
評分採用三等九級制(A+、A、A-、B+、B、B-、C+、C、C-)
""")
# 輸入區塊
with gr.Column():
msg = gr.Textbox(
label="請輸入作文內容",
placeholder="在此輸入作文...",
lines=10
)
additional_prompt = gr.Textbox(
label="額外評分提示(選填)",
placeholder="可輸入額外的評分要求或提示...",
lines=2
)
# 模型選擇
with gr.Row():
provider = gr.Radio(
choices=["openai", "groq"],
label="選擇服務提供者",
value="openai"
)
model = gr.Dropdown(
choices=OPENAI_MODELS,
label="選擇模型",
value="gpt-4o",
interactive=True
)
# 當更換提供者時更新模型選項
provider.change(
fn=update_model_choices,
inputs=provider,
outputs=model
)
# 按鈕區
with gr.Row():
submit = gr.Button("開始評分", variant="primary", size="lg")
clear = gr.Button("清除內容", size="lg")
# 顯示區塊
with gr.Row():
# 左側顯示評分詳情
with gr.Column(scale=2):
chatbot = gr.Chatbot(
show_copy_button=True,
render_markdown=True,
height=600,
label="評分詳情"
)
# 右側顯示總分
with gr.Column(scale=1):
score_display = gr.Markdown("### 等待評分...")
# 事件處理
submit.click(
evaluate_essay,
inputs=[msg, additional_prompt, provider, model],
outputs=[chatbot, score_display]
)
clear.click(
lambda: [None, None, "openai", "gpt-4o", [], gr.Markdown("### 等待評分...")],
outputs=[msg, additional_prompt, provider, model, chatbot, score_display]
)
# 啟動應用
if __name__ == "__main__":
demo.launch() |