Files
python-template/backend/test_gemini_fixed.py
brunoandClaude 15b2471c2f feat: 集成 Google Gemini 3 Pro 模型并修复 JSON 转义问题
## 主要改进

### 🚀 Gemini 3 Pro 集成
- 支持通过 OpenRouter API 调用 Google Gemini 3 Pro Preview 模型
- 针对数学试卷优化 prompt,增强数学公式识别能力
- 自动检测 Gemini 模型并启用数学优化模式
- 设置 Gemini 3 Pro 为默认解析模型(AI_MODEL 环境变量)

### 🔧 JSON 转义修复
- 实现 fix_json_escaping() 函数处理 LaTeX 公式中的反斜杠
- 智能识别并转义 LaTeX 命令(\frac, \sqrt, \pm 等)
- 保留有效的 JSON 转义序列(\", \\, \/, \uXXXX)
- 解决 Gemini 返回的 LaTeX 公式 JSON 解析失败问题

### 📐 数学解析增强
- 详细的 LaTeX 公式转换说明(分数、根式、积分、矩阵等)
- 特殊数学符号支持(不等式、集合、逻辑、箭头等)
- 几何图形识别和描述
- 完整的解题步骤和思路分析

### 📝 新增文件
- GEMINI_INTEGRATION.md: 完整的集成文档
- test_gemini_math.py: Claude vs Gemini 对比测试脚本
- test_gemini_fixed.py: JSON 修复验证测试
- example_gemini_usage.py: 使用示例和最佳实践
- quick_test_gemini.sh: 快速测试脚本

### 🎯 测试结果
- ✅ 成功解析数学试卷(5 道题,100 分)
- ✅ 正确提取所有 LaTeX 公式
- ✅ 详细的解题步骤和知识点标注
- ✅ 准确的难度评估(难度 2-5)

## 配置说明

在 .env 文件中设置:
```bash
AI_MODEL=google/gemini-3-pro-preview
USE_CLAUDE_PARSER=true
```

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
2025-11-22 22:44:37 +08:00

141 lines
4.4 KiB
Python
Executable File

#!/usr/bin/env python3
"""
测试修复后的 Gemini 3 Pro 数学试卷解析
"""
import os
import sys
import json
from dotenv import load_dotenv
from claude_exam_parser import ClaudeExamParser
# 加载环境变量
load_dotenv()
def test_gemini_parsing():
"""测试 Gemini 模型的解析功能"""
# 使用同一份试卷
file_path = "uploads/1/7c6df72c-3386-4909-8e6e-0471930d1284_2025年9月2日初中数学作业.pdf"
if not os.path.exists(file_path):
print(f"❌ 文件不存在: {file_path}")
return
print("="*80)
print("测试修复后的 Gemini 3 Pro 解析功能")
print("="*80)
print()
# 创建解析器,使用 Gemini 模型
parser = ClaudeExamParser(model="google/gemini-3-pro-preview")
print("📄 开始解析试卷...")
print(f" 文件: {file_path}")
print(f" 模型: google/gemini-3-pro-preview")
print()
# 解析
result = parser.parse_exam_file(file_path, subject="数学", grade="初中")
if result["success"]:
data = result["result"]
print("\n" + "="*80)
print("✅ 解析成功!")
print("="*80)
print()
print(f"📚 学科: {data.get('subject', 'N/A')}")
print(f"🎓 年级: {data.get('grade', 'N/A')}")
print(f"📝 考试类型: {data.get('exam_type', 'N/A')}")
print(f"📊 题目总数: {data.get('total_questions', 0)}")
print(f"💯 总分: {data.get('total_score', 'N/A')}")
print()
# 题型统计
stats = data.get("stats", {})
print("📊 题型统计:")
print(f" 选择题: {stats.get('choice_count', 0)}")
print(f" 填空题: {stats.get('fill_blank_count', 0)}")
print(f" 计算题: {stats.get('calculation_count', 0)}")
print(f" 证明题: {stats.get('proof_count', 0)}")
print(f" 解答题: {stats.get('essay_count', 0)}")
print()
# 难度分布
if "difficulty_distribution" in stats:
print("📈 难度分布:")
for level in sorted(stats["difficulty_distribution"].keys()):
count = stats["difficulty_distribution"][level]
print(f" 难度 {level}: {count} 题")
print()
# 显示每道题的详细信息
print("📝 题目详情:")
print()
for i, q in enumerate(data.get("questions", []), 1):
print(f"【题目 {q.get('number', i)}】")
print(f" 类型: {q.get('type', 'N/A')}")
print(f" 分数: {q.get('score', 'N/A')} 分")
print(f" 难度: {q.get('difficulty', 'N/A')}/5")
# 题干(截取前150字)
question_text = q.get('question', '')
if len(question_text) > 150:
question_text = question_text[:150] + "..."
print(f" 题干: {question_text}")
# 公式
formulas = q.get('formulas', [])
if formulas:
print(f" 公式数: {len(formulas)}")
print(f" 示例公式: {formulas[0] if formulas else 'N/A'}")
# 知识点
points = q.get('knowledge_points', [])
if points:
print(f" 知识点: {', '.join(points)}")
# 答案
if q.get('answer'):
answer = q.get('answer', '')
if len(answer) > 50:
answer = answer[:50] + "..."
print(f" 答案: {answer}")
# 是否有解题步骤
if q.get('solution'):
print(f" ✅ 包含详细解题步骤")
# 是否有分析
if q.get('analysis'):
print(f" ✅ 包含题目分析")
print()
# 保存结果
output_file = "test_results/gemini_fixed_result.json"
os.makedirs("test_results", exist_ok=True)
with open(output_file, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
print(f"💾 详细结果已保存到: {output_file}")
return True
else:
print("\n" + "="*80)
print("❌ 解析失败")
print("="*80)
print()
print(f"错误信息: {result.get('error', 'Unknown error')}")
if "raw_response" in result:
print(f"\n原始响应长度: {len(result['raw_response'])} 字符")
return False
if __name__ == "__main__":
success = test_gemini_parsing()
sys.exit(0 if success else 1)