初始化提交
This commit is contained in:
210
api/app.py
Normal file
210
api/app.py
Normal file
@@ -0,0 +1,210 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
古诗词智能查询与解析器 - 后端API
|
||||
简化版本,包含核心功能
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from flask import Flask, request, jsonify
|
||||
from flask_cors import CORS
|
||||
import requests
|
||||
|
||||
# 配置日志
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 创建Flask应用
|
||||
app = Flask(__name__)
|
||||
CORS(app)
|
||||
|
||||
# 配置
|
||||
app.config['JSON_AS_ASCII'] = False
|
||||
|
||||
# AI API配置
|
||||
SK_API_KEY = "sk-fdf7cc1c73504e628ec0119b7e11b8cc"
|
||||
AI_API_URL = "https://api.deepseek.com/v1/chat/completions"
|
||||
|
||||
# 示例诗词数据库
|
||||
SAMPLE_POETRY_DB = [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "静夜思",
|
||||
"author": "李白",
|
||||
"dynasty": "唐",
|
||||
"content": "床前明月光,疑是地上霜。\n举头望明月,低头思故乡。",
|
||||
"type": "抒情",
|
||||
"word_count": "五言",
|
||||
"tags": ["思乡", "月亮", "夜晚"]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "春晓",
|
||||
"author": "孟浩然",
|
||||
"dynasty": "唐",
|
||||
"content": "春眠不觉晓,处处闻啼鸟。\n夜来风雨声,花落知多少。",
|
||||
"type": "山水",
|
||||
"word_count": "五言",
|
||||
"tags": ["春天", "自然", "风景"]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "水调歌头·明月几时有",
|
||||
"author": "苏轼",
|
||||
"dynasty": "宋",
|
||||
"content": "明月几时有?把酒问青天。\n不知天上宫阙,今夕是何年。\n我欲乘风归去,又恐琼楼玉宇,高处不胜寒。\n起舞弄清影,何似在人间。",
|
||||
"type": "抒情",
|
||||
"word_count": "词",
|
||||
"tags": ["中秋", "月亮", "思念"]
|
||||
}
|
||||
]
|
||||
|
||||
def generate_ai_analysis(poetry_title, author, dynasty, purpose, usage, target_audience, depth, focus):
|
||||
"""生成AI解析"""
|
||||
try:
|
||||
system_prompt = f"""你是一位古典文学专家,精通古诗词解析。
|
||||
背景:诗词用于{usage},读者是{target_audience},解析深度为{depth},关注{focus}。
|
||||
要求:提供准确原文、详细注释、深入解读、学习建议。"""
|
||||
|
||||
user_prompt = f"""解析以下诗词:
|
||||
标题:{poetry_title}
|
||||
作者:{author}
|
||||
朝代:{dynasty}
|
||||
目的:{purpose}"""
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_prompt}
|
||||
]
|
||||
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {SK_API_KEY}"
|
||||
}
|
||||
|
||||
data = {
|
||||
"model": "deepseek-chat",
|
||||
"messages": messages,
|
||||
"temperature": 0.7,
|
||||
"max_tokens": 1500
|
||||
}
|
||||
|
||||
response = requests.post(AI_API_URL, headers=headers, json=data, timeout=30)
|
||||
response.raise_for_status()
|
||||
|
||||
return response.json()["choices"][0]["message"]["content"]
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"AI解析失败: {e}")
|
||||
return f"AI解析生成失败: {str(e)}"
|
||||
|
||||
# API路由
|
||||
@app.route('/')
|
||||
def index():
|
||||
return jsonify({
|
||||
"name": "古诗词智能解析器API",
|
||||
"version": "1.0.0",
|
||||
"endpoints": ["/api/poetry", "/api/search", "/api/ai/analyze"]
|
||||
})
|
||||
|
||||
@app.route('/api/poetry', methods=['GET'])
|
||||
def get_poetry():
|
||||
"""获取诗词列表"""
|
||||
try:
|
||||
return jsonify({
|
||||
"success": True,
|
||||
"data": SAMPLE_POETRY_DB,
|
||||
"count": len(SAMPLE_POETRY_DB)
|
||||
})
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
@app.route('/api/search', methods=['GET'])
|
||||
def search():
|
||||
"""搜索诗词"""
|
||||
try:
|
||||
query = request.args.get('q', '').lower()
|
||||
if not query:
|
||||
return jsonify({"success": True, "data": SAMPLE_POETRY_DB})
|
||||
|
||||
results = []
|
||||
for poetry in SAMPLE_POETRY_DB:
|
||||
if (query in poetry['title'].lower() or
|
||||
query in poetry['author'].lower() or
|
||||
query in poetry['content'].lower()):
|
||||
results.append(poetry)
|
||||
|
||||
return jsonify({
|
||||
"success": True,
|
||||
"data": results,
|
||||
"count": len(results)
|
||||
})
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
@app.route('/api/ai/analyze', methods=['POST'])
|
||||
def analyze():
|
||||
"""AI解析诗词"""
|
||||
try:
|
||||
data = request.get_json()
|
||||
|
||||
# 必要参数检查
|
||||
required = ['poetry_title', 'author', 'dynasty']
|
||||
for field in required:
|
||||
if field not in data:
|
||||
return jsonify({
|
||||
"success": False,
|
||||
"error": f"缺少参数: {field}"
|
||||
}), 400
|
||||
|
||||
# 获取参数
|
||||
poetry_title = data['poetry_title']
|
||||
author = data['author']
|
||||
dynasty = data['dynasty']
|
||||
purpose = data.get('purpose', '学习理解')
|
||||
usage = data.get('usage', '课堂教学')
|
||||
target_audience = data.get('target_audience', '中小学生')
|
||||
depth = data.get('depth', '基础')
|
||||
focus = data.get('focus', '综合解析')
|
||||
|
||||
# 生成解析
|
||||
analysis = generate_ai_analysis(
|
||||
poetry_title, author, dynasty, purpose, usage,
|
||||
target_audience, depth, focus
|
||||
)
|
||||
|
||||
return jsonify({
|
||||
"success": True,
|
||||
"data": {
|
||||
"analysis": analysis,
|
||||
"metadata": {
|
||||
"poetry_title": poetry_title,
|
||||
"author": author,
|
||||
"dynasty": dynasty,
|
||||
"timestamp": datetime.now().isoformat()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"解析失败: {e}")
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
@app.route('/api/poetry/<int:poetry_id>', methods=['GET'])
|
||||
def get_poetry_detail(poetry_id):
|
||||
"""获取诗词详情"""
|
||||
try:
|
||||
poetry = next((p for p in SAMPLE_POETRY_DB if p['id'] == poetry_id), None)
|
||||
if not poetry:
|
||||
return jsonify({"success": False, "error": "诗词未找到"}), 404
|
||||
|
||||
return jsonify({"success": True, "data": poetry})
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
if __name__ == '__main__':
|
||||
logger.info("启动古诗词智能解析器API服务器...")
|
||||
app.run(host='0.0.0.0', port=5000, debug=True)
|
||||
Reference in New Issue
Block a user