You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
3.9 KiB

5 months ago
import os
import json
from typing import Iterator
from openai import OpenAI
class EnglishEssayAnalyzer:
def __init__(self):
self.client = OpenAI(
api_key=os.getenv("DEEPSEEK_API_KEY", "sk-01d13a39e09844038322108ecdbd1bbc"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)
def _build_prompt(self, essay: str) -> str:
return f"""你是一位专业的英语教师,请分析以下英文作文:
{essay}
请按以下顺序指出问题
1. 语法错误标注行号
2. 用词不当
3. 逻辑结构问题
4. 改进建议
用中文回答保持专业但易懂的语气"""
def analyze_stream(self, essay: str) -> Iterator[str]:
"""流式分析作文"""
try:
stream = self.client.chat.completions.create(
model="deepseek-r1",
messages=[{
"role": "user",
"content": self._build_prompt(essay)
}],
temperature=0.3,
stream=True
)
buffer = []
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
content = chunk.choices[0].delta.content
buffer.append(content)
# 遇到标点或换行时输出完整句子
if content in ('\n', '.', '!', '?', ''):
yield ''.join(buffer)
buffer = []
else:
yield content
if buffer:
yield ''.join(buffer)
except Exception as e:
yield f"\n分析中断:{str(e)}"
def full_analysis(self, essay: str) -> dict:
"""完整分析并返回结构化结果"""
analysis = {
"grammar_errors": [],
"vocabulary_issues": [],
"structure_problems": [],
"suggestions": []
}
current_category = None
for chunk in self.analyze_stream(essay):
# 实时输出
print(chunk, end='', flush=True)
# 解析结构
if chunk.strip().endswith(''):
current_category = chunk.strip(' ')
elif current_category:
if '语法错误' in current_category:
analysis['grammar_errors'].append(chunk.strip())
elif '用词不当' in current_category:
analysis['vocabulary_issues'].append(chunk.strip())
elif '逻辑结构' in current_category:
analysis['structure_problems'].append(chunk.strip())
elif '改进建议' in current_category:
analysis['suggestions'].append(chunk.strip())
return analysis
if __name__ == "__main__":
# 示例用法
essay = """
Dear Peter Knowing that you have won the first prize in The Chinese Chess NetworkChallengeCompetition I feel very delighted. I'm writing to offer my warmest congratulations to you. From my perspective you derseve what you gained What lead to your success is your diligence and go all out for the contest making me admire you. On top of this It's real encouragement to me to see your effors pay off. How I marvel at your perfect performance which inspires my passion on Chinese Chess and other traditional skills I would appreciate if you could share with me your experience on learn it. Looking forward to your early reply Your sincerely
"""
analyzer = EnglishEssayAnalyzer()
print("🔍 开始分析作文...\n")
result = analyzer.full_analysis(essay)
# 保存结果
with open("analysis_report.json", "w", encoding="utf-8") as f:
json.dump(result, f, ensure_ascii=False, indent=2)
print("\n\n✅ 分析结果已保存至 analysis_report.json")