-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapp.py
More file actions
951 lines (802 loc) · 33 KB
/
Copy pathapp.py
File metadata and controls
951 lines (802 loc) · 33 KB
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
from flask import Flask, request, render_template, jsonify, Response, redirect, url_for, send_file
import asyncio
import json
import os
import re
import uuid
import datetime
from threading import Thread
from queue import Queue
from main import (
handler_letter_correct,
handler_letter_correct_async,
handler_letter_correct_async_with_provider,
get_task_handler_by_provider,
log_llm_response,
handler_letter_correct_stream
)
from logger import setup_logger
from models import db, CorrectionHistory, init_db
import csv
import io
from werkzeug.utils import secure_filename
app = Flask(__name__)
# 配置数据库
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///correction_history.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# 初始化数据库
init_db(app)
# 配置日志
logger = setup_logger(__name__)
# 任务队列与结果缓存
task_queue = Queue()
results_cache = {}
stream_results = {} # 存储流式响应结果
# 批改历史记录存储
correction_history = {} # 使用内存存储批改历史记录
# 注意:在异步函数中使用数据库操作时,必须确保在应用上下文中执行
# 可以使用 with app.app_context(): 或者调用 save_history_async 辅助函数
def save_correction_to_history(essay: str, result: dict, mode: str = "sync") -> str:
"""
保存批改结果到历史记录
:param essay: 用户提交的作文
:param result: 批改结果
:param mode: 批改模式(sync/async/stream)
:return: 历史记录ID
"""
try:
history_id = str(uuid.uuid4())
# 提取评分
score = "未评分"
if result and "评分" in result and "分数" in result["评分"]:
score = result["评分"]["分数"]
# 统计错误数量
error_count = count_errors(result)
# 创建数据库记录
history_record = CorrectionHistory(
id=history_id,
essay=essay,
result=result,
mode=mode,
score=score,
error_count=error_count
)
# 保存到数据库
db.session.add(history_record)
db.session.commit()
logger.info(f"批改历史已保存到数据库,ID: {history_id}, 模式: {mode}, 分数: {score}")
return history_id
except Exception as e:
logger.error(f"保存批改历史失败: {str(e)}")
# 尝试回滚事务
try:
db.session.rollback()
except Exception as rollback_error:
logger.error(f"回滚事务失败: {str(rollback_error)}")
return ""
def process_essay(essay: str):
"""
处理作文并返回批改结果。
:param essay: 用户提交的作文
:return: 批改结果
"""
try:
# 记录作文内容到日志目录
save_essay_to_log(essay, "sync")
# 调用批改函数
result = handler_letter_correct(essay)
# 记录返回数据摘要
logger.info(f"批改完成,错误数量: {count_errors(result)}")
# 保存到历史记录
history_id = save_correction_to_history(essay, result, "sync")
if history_id:
result["history_id"] = history_id
return result
except Exception as e:
logger.error(f"批改失败: {str(e)}")
raise
def count_errors(result):
"""统计错误数量"""
total = 0
for category, errors in result.get('错误分析', {}).items():
total += len(errors)
return total
def save_essay_to_log(essay, mode="sync"):
"""保存作文内容到日志文件"""
try:
# 确保日志目录存在
log_dir = os.path.join(os.getcwd(), 'logs')
if not os.path.exists(log_dir):
os.makedirs(log_dir)
# 创建唯一文件名
import datetime
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
log_file = os.path.join(log_dir, f'essay_{mode}_{timestamp}.txt')
# 写入作文内容
with open(log_file, 'w', encoding='utf-8') as f:
f.write(essay)
logger.info(f"作文内容已保存到 {log_file}")
except Exception as e:
logger.error(f"保存作文失败: {str(e)}")
async def process_essay_async(essay: str, task_id: str):
"""
异步处理作文
:param essay: 用户提交的作文
:param task_id: 任务ID
"""
try:
# 记录作文内容到日志
save_essay_to_log(essay, f"async_{task_id}")
# 调用异步批改函数
result = await handler_letter_correct_async(essay)
# 保存到历史记录(使用辅助函数)
history_id = await save_history_async(essay, result, "async")
if history_id:
result["history_id"] = history_id
# 更新任务状态
results_cache[task_id].update({
"status": "completed",
"result": result
})
# 记录完成信息
logger.info(f"任务 {task_id} 完成,错误数量: {count_errors(result)}")
except Exception as e:
results_cache[task_id].update({
"status": "error",
"error": str(e)
})
logger.error(f"任务 {task_id} 失败: {str(e)}")
async def process_stream_essay(essay: str, task_id: str):
"""
流式处理作文
:param essay: 用户提交的作文
:param task_id: 任务ID
"""
try:
# 记录作文内容
save_essay_to_log(essay, f"stream_{task_id}")
# 初始化结果存储
stream_results[task_id] = {
"status": "processing",
"last_chunk": None,
"partial_result": {},
"final_result": None,
"essay": essay,
"updates_count": 0 # 添加更新计数器
}
# 调用流式批改函数
async for chunk in handler_letter_correct_stream(essay):
# 更新最新的块数据
stream_results[task_id]["last_chunk"] = chunk
stream_results[task_id]["updates_count"] += 1
# 如果有部分结果,更新部分结果
if "partial_result" in chunk:
stream_results[task_id]["partial_result"] = chunk["partial_result"] # 完全替换,不是更新
logger.info(f"流式任务 {task_id} 更新第 {stream_results[task_id]['updates_count']} 次,获得部分结果")
# 如果处理完成,保存最终结果
if chunk.get("status") == "completed":
stream_results[task_id]["status"] = "completed"
stream_results[task_id]["final_result"] = chunk.get("result")
# 保存到历史记录(使用辅助函数)
if "result" in chunk:
history_id = await save_history_async(essay, chunk["result"], "stream")
if history_id:
stream_results[task_id]["history_id"] = history_id
logger.info(f"流式任务 {task_id} 完成")
break
# 如果出错,记录错误
if chunk.get("status") == "error":
stream_results[task_id]["status"] = "error"
stream_results[task_id]["error"] = chunk.get("error")
logger.error(f"流式任务 {task_id} 失败: {chunk.get('error')}")
break
except Exception as e:
stream_results[task_id]["status"] = "error"
stream_results[task_id]["error"] = str(e)
logger.error(f"流式任务 {task_id} 处理异常: {str(e)}")
# 双引擎批改函数(目前是框架,尚未实现具体功能)
async def process_dual_engine_async(essay: str, task_id: str):
"""
使用双引擎批改作文(DeepSeek + OpenAI)
:param essay: 用户提交的作文
:param task_id: 任务ID
"""
try:
# 记录作文内容
save_essay_to_log(essay, f"dual_{task_id}")
# 初始化结果状态
results_cache[task_id].update({
"status": "processing_dual_engine",
"progress": "正在使用双引擎进行批改..."
})
# 并行调用 DeepSeek / OpenAI 两个引擎
result = await dual_engine_correct_async(essay)
# 保存到历史记录(使用辅助函数)
history_id = await save_history_async(essay, result, "dual")
if history_id:
result["history_id"] = history_id
# 更新任务状态
results_cache[task_id].update({
"status": "completed",
"result": result,
"engine": "dual"
})
logger.info(f"双引擎任务 {task_id} 完成")
except Exception as e:
results_cache[task_id].update({
"status": "error",
"error": str(e)
})
logger.error(f"双引擎任务 {task_id} 失败: {str(e)}")
def _normalize_score(score_value):
"""将评分归一化为数值,无法解析时返回None。"""
if isinstance(score_value, (int, float)):
return float(score_value)
if isinstance(score_value, str):
text = score_value.strip()
if not text:
return None
# 先尝试直接解析纯数字/小数
try:
return float(text)
except ValueError:
pass
# 处理类似 "18/20" 的格式,优先取分子作为得分值
fraction_match = re.search(r"(-?\d+(?:\.\d+)?)\s*/\s*(-?\d+(?:\.\d+)?)", text)
if fraction_match:
try:
return float(fraction_match.group(1))
except ValueError:
return None
# 兜底:提取第一个数字(支持小数)
first_number_match = re.search(r"-?\d+(?:\.\d+)?", text)
if first_number_match:
try:
return float(first_number_match.group(0))
except ValueError:
return None
return None
def merge_dual_engine_results(
primary: dict, secondary: dict, primary_provider: str = "deepseek", secondary_provider: str = "openai"
) -> dict:
"""
合并双引擎结果:主引擎为 DeepSeek,辅引擎为 OpenAI。
"""
merged = dict(primary or {})
primary_error = (primary or {}).get("错误分析", {})
secondary_error = (secondary or {}).get("错误分析", {})
merged_error = {}
categories = set(primary_error.keys()) | set(secondary_error.keys())
for category in categories:
primary_items = primary_error.get(category, []) or []
secondary_items = secondary_error.get(category, []) or []
seen = set()
merged_items = []
for item in primary_items + secondary_items:
item_key = (
item.get("错误文本"),
tuple(item.get("错误位置", [])),
item.get("错误说明"),
item.get("修改建议"),
)
if item_key in seen:
continue
seen.add(item_key)
merged_items.append(item)
merged_error[category] = merged_items
merged["错误分析"] = merged_error
primary_highlights = (primary or {}).get("亮点分析", {})
secondary_highlights = (secondary or {}).get("亮点分析", {})
merged_highlights = {}
highlight_categories = set(primary_highlights.keys()) | set(secondary_highlights.keys())
for category in highlight_categories:
p = primary_highlights.get(category, []) or []
s = secondary_highlights.get(category, []) or []
merged_highlights[category] = list(dict.fromkeys(p + s))
merged["亮点分析"] = merged_highlights
p_score_text = (primary or {}).get("评分", {}).get("分数")
s_score_text = (secondary or {}).get("评分", {}).get("分数")
p_score = _normalize_score(p_score_text)
s_score = _normalize_score(s_score_text)
if p_score is not None and s_score is not None:
avg_score = round((p_score + s_score) / 2)
merged.setdefault("评分", {})
merged["评分"]["分数"] = str(avg_score)
secondary_suggestion = (secondary or {}).get("写作建议")
if secondary_suggestion:
merged["写作建议"] = f"{(primary or {}).get('写作建议', '')}\n\n【交叉校验补充】\n{secondary_suggestion}".strip()
merged["双引擎详情"] = {
"mode": "dual_engine",
"primary_engine": primary_provider,
"secondary_engine": secondary_provider,
"primary_result": primary,
"secondary_result": secondary
}
return merged
def _resolve_dual_engine_providers() -> list[str]:
"""
读取双引擎 provider 配置,并过滤出当前可用 provider 列表。
"""
configured_providers: list[str] = []
try:
with open("config.json", "r", encoding="utf-8") as f:
config = json.load(f)
dual_engine = config.get("model", {}).get("dual_engine", {})
configured_providers = dual_engine.get("providers", [])
if not configured_providers:
primary = dual_engine.get("primary_provider", "deepseek")
secondary = dual_engine.get("secondary_provider", "openai")
configured_providers = [primary, secondary]
except Exception:
configured_providers = ["deepseek", "openai"]
unique_providers = list(dict.fromkeys([provider for provider in configured_providers if provider]))
available_providers: list[str] = []
for provider in unique_providers:
try:
get_task_handler_by_provider(provider)
available_providers.append(provider)
except Exception as e:
logger.warning(f"provider 不可用,已跳过: provider={provider}, error={e}")
if not available_providers:
raise ValueError("未找到可用的双引擎 provider,请检查 dual_engine 配置或 API Key")
return available_providers
def _degraded_dual_result(primary_result: dict, primary_provider: str, secondary_provider: str, reason: str) -> dict:
"""
当第二引擎不可用时,回退为单引擎结果并附带降级信息。
"""
degraded = dict(primary_result or {})
degraded["双引擎详情"] = {
"mode": "degraded_single_engine",
"primary_engine": primary_provider,
"secondary_engine": secondary_provider,
"degraded_reason": reason,
"primary_result": primary_result,
"secondary_result": None
}
return degraded
async def dual_engine_correct_async(essay: str) -> dict:
"""
双引擎并行批改(DeepSeek + OpenAI)并合并结果。
"""
available_providers = _resolve_dual_engine_providers()
primary_provider = available_providers[0]
secondary_provider = available_providers[1] if len(available_providers) > 1 else None
if secondary_provider is None:
primary_result = await handler_letter_correct_async_with_provider(essay, primary_provider)
return _degraded_dual_result(
primary_result,
primary_provider,
"unavailable",
"仅检测到一个可用模型,双引擎自动降级为单引擎"
)
primary_task = handler_letter_correct_async_with_provider(essay, primary_provider)
secondary_task = handler_letter_correct_async_with_provider(essay, secondary_provider)
primary_result, secondary_result = await asyncio.gather(
primary_task, secondary_task, return_exceptions=True
)
if isinstance(primary_result, Exception):
if not isinstance(secondary_result, Exception):
logger.warning(
f"双引擎降级为单引擎: primary_provider={primary_provider}, error={primary_result}"
)
return _degraded_dual_result(
secondary_result,
secondary_provider,
primary_provider,
f"{primary_provider} 失败,自动降级为 {secondary_provider}: {primary_result}"
)
raise primary_result
if isinstance(secondary_result, Exception):
logger.warning(
f"双引擎降级为单引擎: secondary_provider={secondary_provider}, error={secondary_result}"
)
return _degraded_dual_result(
primary_result, primary_provider, secondary_provider, str(secondary_result)
)
return merge_dual_engine_results(primary_result, secondary_result, primary_provider, secondary_provider)
def background_task_processor():
"""
后台任务处理线程
"""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
while True:
if not task_queue.empty():
task = task_queue.get()
essay = task["essay"]
task_id = task["task_id"]
task_type = task.get("type", "async")
logger.info(f"开始处理{task_type}任务 {task_id}")
# 更新任务状态为处理中
if task_type == "stream":
# 流式处理
loop.run_until_complete(process_stream_essay(essay, task_id))
elif task_type == "dual":
# 双引擎处理
results_cache[task_id].update({"status": "processing"})
loop.run_until_complete(process_dual_engine_async(essay, task_id))
else:
# 常规异步处理
results_cache[task_id].update({"status": "processing"})
loop.run_until_complete(process_essay_async(essay, task_id))
task_queue.task_done()
# 启动后台任务处理线程
background_thread = Thread(target=background_task_processor, daemon=True)
background_thread.start()
@app.route("/", methods=["GET", "POST"])
def index():
"""
处理首页请求。
"""
if request.method == "POST":
essay = request.form.get("essay")
process_type = request.form.get("process_type", "sync")
engine_type = request.form.get("engine_type", "single")
if not essay:
logger.warning("提交了空作文")
return render_template("index.html", error="请提交一篇作文!")
logger.info(f"收到作文批改请求,内容长度: {len(essay)} 字符,处理方式: {process_type},引擎类型: {engine_type}")
# 只有同步处理在这里处理,其他方式通过JavaScript AJAX提交
if process_type == "sync":
try:
# 同步处理模式
if engine_type == "dual":
logger.info("同步双引擎已下线,自动回退到单引擎同步批改")
result = process_essay(essay)
return render_template("result.html", essay=essay, result=result)
except Exception as e:
logger.error(f"处理作文时出错: {str(e)}")
return render_template("index.html", error=f"批改失败: {str(e)}")
return render_template("index.html")
@app.route("/api/submit", methods=["POST"])
def api_submit():
"""
API端点 - 提交作文进行异步处理
"""
essay = request.json.get("essay")
engine_type = request.json.get("engine", "single") # 默认使用单引擎
if not essay:
logger.warning("API收到空作文请求")
return jsonify({"error": "请提交作文内容"}), 400
logger.info(f"收到异步作文批改请求,内容长度: {len(essay)} 字符,引擎类型: {engine_type}")
# 生成任务ID
task_id = str(uuid.uuid4())
logger.info(f"生成任务ID: {task_id}")
# 加入任务队列
task_queue.put({
"essay": essay,
"task_id": task_id,
"type": "dual" if engine_type == "dual" else "async"
})
# 初始化任务状态
results_cache[task_id] = {
"status": "queued",
"essay": essay, # 保存原始作文文本
"engine": engine_type
}
return jsonify({
"task_id": task_id,
"status": "queued"
})
@app.route("/api/submit-sync", methods=["POST"])
def api_submit_sync():
"""
API端点 - 同步提交作文并直接返回结果
"""
payload = request.json or {}
essay = payload.get("essay")
engine_type = payload.get("engine", "single")
if not essay:
return jsonify({"error": "请提交作文内容"}), 400
try:
if engine_type == "dual":
return jsonify({
"status": "error",
"error": "同步双引擎已下线,请改用 /api/submit 异步双引擎"
}), 400
result = process_essay(essay)
return jsonify({
"status": "completed",
"engine": engine_type,
"result": result
})
except Exception as e:
logger.error(f"同步API批改失败: {str(e)}")
return jsonify({"status": "error", "error": str(e)}), 500
@app.route("/api/status/<task_id>", methods=["GET"])
def api_status(task_id):
"""
API端点 - 检查任务状态
"""
if task_id not in results_cache:
logger.warning(f"请求了不存在的任务ID: {task_id}")
return jsonify({"error": "任务不存在"}), 404
status_data = results_cache[task_id]
logger.debug(f"任务 {task_id} 状态: {status_data.get('status')}")
# 如果任务完成,返回结果
if status_data.get("status") == "completed":
result_data = status_data.get("result") or {}
dual_detail = result_data.get("双引擎详情", {})
degraded = dual_detail.get("mode") == "degraded_single_engine"
return jsonify({
"status": "completed",
"result": result_data,
"degraded": degraded,
"degraded_reason": dual_detail.get("degraded_reason") if degraded else None,
"dual_engine_mode": dual_detail.get("mode")
})
# 如果任务出错,返回错误信息
if status_data.get("status") == "error":
return jsonify({
"status": "error",
"error": status_data.get("error")
})
# 其他状态
return jsonify({
"status": status_data.get("status")
})
@app.route("/async-result/<task_id>")
def async_result(task_id):
"""
显示异步任务结果页面
"""
if task_id not in results_cache:
logger.warning(f"尝试访问不存在的任务结果: {task_id}")
return render_template("index.html", error="任务不存在")
status_data = results_cache[task_id]
if status_data.get("status") == "completed":
result = status_data.get("result")
essay = status_data.get("essay", "")
logger.info(f"显示任务 {task_id} 的结果")
return render_template("result.html", essay=essay, result=result)
if status_data.get("status") == "error":
error = status_data.get("error")
logger.error(f"显示任务 {task_id} 的错误: {error}")
return render_template("index.html", error=f"批改失败: {error}")
# 如果任务还在处理中,显示等待页面
logger.info(f"任务 {task_id} 仍在处理中,显示等待页面")
return render_template("waiting.html", task_id=task_id)
@app.route("/api/stream", methods=["POST"])
def api_stream_submit():
"""
API端点 - 提交作文进行流式处理
"""
essay = request.json.get("essay")
if not essay:
logger.warning("API收到空作文流式请求")
return jsonify({"error": "请提交作文内容"}), 400
logger.info(f"收到流式作文批改请求,内容长度: {len(essay)} 字符")
# 生成任务ID
task_id = str(uuid.uuid4())
logger.info(f"生成流式任务ID: {task_id}")
# 加入任务队列
task_queue.put({
"essay": essay,
"task_id": task_id,
"type": "stream"
})
# 初始化流式任务状态
stream_results[task_id] = {
"status": "queued",
"essay": essay,
"partial_result": {}
}
return jsonify({
"task_id": task_id,
"status": "queued"
})
@app.route("/api/stream-status/<task_id>", methods=["GET"])
def api_stream_status(task_id):
"""
API端点 - 获取流式处理状态和部分结果
"""
if task_id not in stream_results:
logger.warning(f"请求了不存在的流式任务ID: {task_id}")
return jsonify({"error": "任务不存在"}), 404
status_data = stream_results[task_id]
logger.debug(f"流式任务 {task_id} 状态: {status_data.get('status')}")
# 构建响应数据
response_data = {
"status": status_data.get("status", "unknown"),
"partial_result": status_data.get("partial_result", {})
}
# 如果任务完成,返回最终结果
if status_data.get("status") == "completed":
response_data["complete"] = True
response_data["result"] = status_data.get("final_result")
# 如果任务出错,返回错误信息
if status_data.get("status") == "error":
response_data["error"] = status_data.get("error")
return jsonify(response_data)
@app.route("/stream-result/<task_id>")
def stream_result(task_id):
"""
显示流式任务结果页面
"""
if task_id not in stream_results:
logger.warning(f"尝试访问不存在的流式任务结果: {task_id}")
return render_template("index.html", error="流式任务不存在")
status_data = stream_results[task_id]
essay = status_data.get("essay", "")
# 无论任务是否完成,都直接进入结果页面,通过JavaScript获取实时更新
logger.info(f"显示流式任务 {task_id} 的结果页面")
# 如果已经完成,传递最终结果
if status_data.get("status") == "completed":
result = status_data.get("final_result")
return render_template("result.html", essay=essay, result=result, task_id=task_id, stream_mode=True, is_completed=True)
# 如果出错,返回错误信息
if status_data.get("status") == "error":
error = status_data.get("error")
logger.error(f"显示流式任务 {task_id} 的错误: {error}")
return render_template("index.html", error=f"批改失败: {error}")
# 如果任务还在处理中,传递部分结果(如果有)
partial_result = status_data.get("partial_result", {})
return render_template("result.html", essay=essay, result=partial_result, task_id=task_id, stream_mode=True, is_completed=False)
@app.route("/api/sample/<sample_id>")
def api_sample(sample_id):
"""
API端点 - 获取示例作文内容
:param sample_id: 示例作文ID
:return: 示例作文内容的JSON响应
"""
try:
# 安全检查,防止路径遍历
if sample_id.startswith('.') or '/' in sample_id or '\\' in sample_id:
logger.warning(f"尝试访问不安全的示例作文ID: {sample_id}")
return jsonify({"error": "无效的示例作文ID"}), 400
# 构建示例文件路径
sample_file = os.path.join('static', 'samples', f"{sample_id}.txt")
# 检查文件是否存在
if not os.path.exists(sample_file):
logger.warning(f"请求了不存在的示例作文: {sample_id}")
return jsonify({"error": "示例作文不存在"}), 404
# 读取示例作文内容
with open(sample_file, 'r', encoding='utf-8') as f:
content = f.read()
logger.info(f"提供示例作文: {sample_id}")
return jsonify({"content": content})
except Exception as e:
logger.error(f"获取示例作文时出错: {str(e)}")
return jsonify({"error": f"获取示例作文失败: {str(e)}"}), 500
# 添加批改历史记录路由
@app.route("/history")
def correction_history_page():
"""
显示批改历史记录列表
"""
# 从数据库中查询所有历史记录并按时间倒序排序
history_records = CorrectionHistory.query.order_by(CorrectionHistory.timestamp.desc()).all()
return render_template("history.html", history_records=history_records)
@app.route("/history/<history_id>")
def view_history_detail(history_id):
"""
查看特定历史记录的详细信息
:param history_id: 历史记录ID
"""
# 从数据库中查询指定ID的历史记录
record = CorrectionHistory.query.get(history_id)
if not record:
return render_template("error.html", message="未找到该历史记录")
return render_template("result.html",
essay=record.essay,
result=record.result,
from_history=True,
history_id=record.id,
timestamp=record.formatted_time)
@app.route("/history/delete/<history_id>", methods=["POST"])
def delete_history(history_id):
"""
删除指定的历史记录
:param history_id: 历史记录ID
:return: JSON响应
"""
try:
# 查询指定ID的历史记录
record = CorrectionHistory.query.get(history_id)
if not record:
return jsonify({"success": False, "error": "未找到该历史记录"}), 404
# 从数据库中删除
db.session.delete(record)
db.session.commit()
logger.info(f"已删除历史记录,ID: {history_id}")
return jsonify({"success": True})
except Exception as e:
db.session.rollback()
logger.error(f"删除历史记录失败: {str(e)}")
return jsonify({"success": False, "error": str(e)}), 500
@app.route("/history/clear", methods=["POST"])
def clear_history():
"""
清空所有历史记录
:return: JSON响应
"""
try:
# 删除所有历史记录
CorrectionHistory.query.delete()
db.session.commit()
logger.info("已清空所有历史记录")
return jsonify({"success": True})
except Exception as e:
db.session.rollback()
logger.error(f"清空历史记录失败: {str(e)}")
return jsonify({"success": False, "error": str(e)}), 500
@app.route("/history/export", methods=["GET"])
def export_history():
"""
导出所有历史记录为CSV文件
:return: CSV文件下载
"""
try:
# 查询所有历史记录
records = CorrectionHistory.query.order_by(CorrectionHistory.timestamp.desc()).all()
# 创建CSV文件
output = io.StringIO()
writer = csv.writer(output)
# 写入CSV头部
writer.writerow(['ID', '作文内容', '批改时间', '批改模式', '评分', '错误数量', '作文长度'])
# 写入数据
for record in records:
writer.writerow([
record.id,
record.essay,
record.formatted_time,
record.mode,
record.score,
record.error_count,
record.essay_length
])
# 准备文件下载
output.seek(0)
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
return send_file(
io.BytesIO(output.getvalue().encode('utf-8-sig')), # 使用UTF-8-SIG编码以支持Excel正确显示中文
mimetype='text/csv',
as_attachment=True,
download_name=f'批改历史记录_{timestamp}.csv'
)
except Exception as e:
logger.error(f"导出历史记录失败: {str(e)}")
return render_template("error.html", message=f"导出历史记录失败: {str(e)}")
@app.route("/history/export/<history_id>", methods=["GET"])
def export_single_history(history_id):
"""
导出单条历史记录为JSON文件
:param history_id: 历史记录ID
:return: JSON文件下载
"""
try:
# 查询指定ID的历史记录
record = CorrectionHistory.query.get(history_id)
if not record:
return render_template("error.html", message="未找到该历史记录")
# 转换为字典
record_dict = record.to_dict()
# 准备JSON文件下载
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
return send_file(
io.BytesIO(json.dumps(record_dict, ensure_ascii=False, indent=2).encode('utf-8')),
mimetype='application/json',
as_attachment=True,
download_name=f'批改记录_{history_id}_{timestamp}.json'
)
except Exception as e:
logger.error(f"导出单条历史记录失败: {str(e)}")
return render_template("error.html", message=f"导出历史记录失败: {str(e)}")
async def save_history_async(essay: str, result: dict, mode: str = "sync") -> str:
"""
在异步环境中安全地保存历史记录
:param essay: 用户提交的作文
:param result: 批改结果
:param mode: 批改模式(sync/async/stream)
:return: 历史记录ID
"""
try:
with app.app_context():
history_id = save_correction_to_history(essay, result, mode)
return history_id
except Exception as e:
logger.error(f"异步环境中保存历史记录失败: {str(e)}")
return ""
if __name__ == "__main__":
logger.info("启动应用服务器...")
app.run(debug=True, port=5000, host='0.0.0.0')