update code
This commit is contained in:
210
app.py
210
app.py
@@ -1,5 +1,6 @@
|
||||
from asyncio import timeout
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from flask import Flask, render_template, jsonify, request
|
||||
import json
|
||||
import os
|
||||
@@ -45,7 +46,7 @@ class MessageRender:
|
||||
else:
|
||||
display_parts.append(f'[{msg_type}]')
|
||||
message_data['display_content'] = ' '.join(display_parts)
|
||||
except:
|
||||
except ValueError:
|
||||
message_data['display_content'] = '[混合消息]'
|
||||
elif msg_type == 'chatrecord':
|
||||
try:
|
||||
@@ -55,7 +56,7 @@ class MessageRender:
|
||||
message_data['chatrecord_data'] = chatrecord_data
|
||||
else:
|
||||
message_data['display_content'] = '[聊天记录]'
|
||||
except:
|
||||
except ValueError:
|
||||
message_data['display_content'] = '[聊天记录]'
|
||||
else:
|
||||
message_data['display_content'] = f'[{msg_type}] {content}'
|
||||
@@ -384,10 +385,10 @@ class ReportService:
|
||||
def analyze_category_breakdown(messages):
|
||||
"""分析问题分类"""
|
||||
category_counts = {
|
||||
'信息披露类': 0,
|
||||
'公司治理与法规': 0,
|
||||
'业务操作与系统': 0,
|
||||
'其他': 0
|
||||
'信息披露类': 0.0,
|
||||
'公司治理与法规': 0.0,
|
||||
'业务操作与系统': 0.0,
|
||||
'其他': 0.0
|
||||
}
|
||||
|
||||
category_keywords = {
|
||||
@@ -474,43 +475,47 @@ message_processor = MessageRender()
|
||||
chat_session = ChatSessionManager(db_manager)
|
||||
|
||||
|
||||
def api_response(success=True, data=None, error=None, status_code=200):
|
||||
def api_response(success=True, data=None, error = None, status_code=200):
|
||||
"""统一的API响应格式"""
|
||||
response = {'success': success}
|
||||
if data:
|
||||
response.update(data)
|
||||
if error:
|
||||
response['error'] = str(error)
|
||||
if data:
|
||||
response.update(data)
|
||||
return jsonify(response), status_code
|
||||
|
||||
|
||||
# 页面路由
|
||||
@app.route('/', defaults={'timeout': 60})
|
||||
@app.route('/')
|
||||
def index():
|
||||
"""主页面 - 聊天界面"""
|
||||
return render_template('index.html')
|
||||
|
||||
|
||||
@app.route('/qa', defaults={'timeout': 60})
|
||||
@app.route('/qa')
|
||||
def qa_page():
|
||||
"""问答管理页面"""
|
||||
return render_template('qa.html')
|
||||
|
||||
|
||||
@app.route('/weekly_report', defaults={'timeout': 60})
|
||||
@app.route('/weekly_report')
|
||||
def weekly_report_page():
|
||||
"""周报页面"""
|
||||
return render_template('weekly_report.html')
|
||||
|
||||
|
||||
@app.route('/daily_report', defaults={'timeout': 60})
|
||||
@app.route('/daily_report')
|
||||
def daily_report_page():
|
||||
"""日报页面"""
|
||||
return render_template('daily_report.html')
|
||||
@app.route('/api/db/datetime', defaults={'timeout': 60})
|
||||
|
||||
|
||||
@app.route('/api/db/datetime')
|
||||
def db_status():
|
||||
return api_response(success=True, data={'message': chat_session.status()})
|
||||
@app.route('/api/db/update', defaults={'timeout': 60})
|
||||
|
||||
|
||||
@app.route('/api/db/update')
|
||||
def db_update():
|
||||
current_time = time.localtime(time.time() - 24 * 60 * 60)
|
||||
day = current_time.tm_mday
|
||||
@@ -528,7 +533,7 @@ def db_update():
|
||||
return api_response(success=True, data={'message': '数据库更新成功'})
|
||||
|
||||
|
||||
@app.route('/api/db/upload', defaults={'timeout': 60})
|
||||
@app.route('/api/db/upload')
|
||||
def db_upload():
|
||||
db_manager.upload_db()
|
||||
return api_response(success=True, data={'message': '数据库上传成功'})
|
||||
@@ -655,32 +660,151 @@ def search_messages():
|
||||
try:
|
||||
keyword = request.args.get('keyword', '')
|
||||
limit = request.args.get('limit', 100, type=int)
|
||||
search_type = request.args.get('search_type', 'all') # all, question, answer
|
||||
|
||||
if not keyword:
|
||||
return api_response(success=False, error='请输入搜索关键词', status_code=400)
|
||||
|
||||
group_id = request.args.get('group_id', type=str)
|
||||
|
||||
# 智能搜索:支持模糊匹配和精确匹配
|
||||
messages_data = report_service.search_messages(keyword, limit, group_id)
|
||||
|
||||
# 根据搜索类型过滤消息
|
||||
if search_type == 'question':
|
||||
messages_data = [msg for msg in messages_data if msg.get('type') in ['text', 'mixed']]
|
||||
elif search_type == 'answer':
|
||||
messages_data = [msg for msg in messages_data if msg.get('type') in ['text', 'mixed']]
|
||||
|
||||
formatted_messages = []
|
||||
for msg in messages_data:
|
||||
message = dict(msg)
|
||||
message = message_processor.process_message_content(message)
|
||||
|
||||
# 添加搜索关键词高亮
|
||||
if keyword:
|
||||
content = message.get('content', '')
|
||||
if keyword.lower() in content.lower():
|
||||
# 简单的关键词高亮(前端可以进一步处理)
|
||||
highlighted_content = content.replace(keyword, f'<mark>{keyword}</mark>')
|
||||
message['highlighted_content'] = highlighted_content
|
||||
|
||||
formatted_messages.append(message)
|
||||
|
||||
return api_response(data={'messages': formatted_messages})
|
||||
return api_response(data={'messages': formatted_messages, 'total': len(formatted_messages)})
|
||||
|
||||
except Exception as e:
|
||||
return api_response(success=False, error=e, status_code=500)
|
||||
|
||||
|
||||
# API路由 - 搜索建议
|
||||
@app.route('/api/search_suggestions')
|
||||
def search_suggestions():
|
||||
"""搜索建议API"""
|
||||
try:
|
||||
keyword = request.args.get('keyword', '')
|
||||
|
||||
if not keyword:
|
||||
return api_response(data={'suggestions': []})
|
||||
|
||||
# 获取热门搜索关键词
|
||||
suggestions = []
|
||||
|
||||
# 1. 从消息内容中提取相关关键词
|
||||
try:
|
||||
messages = report_service.search_messages(keyword, 10, None)
|
||||
for msg in messages:
|
||||
content = msg.get('content', '')
|
||||
# 简单的关键词提取逻辑
|
||||
words = content.split()
|
||||
for word in words:
|
||||
if len(word) > 2 and keyword.lower() in word.lower():
|
||||
if word not in suggestions:
|
||||
suggestions.append(word)
|
||||
if len(suggestions) >= 5:
|
||||
break
|
||||
if len(suggestions) >= 5:
|
||||
break
|
||||
except:
|
||||
pass
|
||||
|
||||
# 2. 添加常见搜索关键词
|
||||
common_keywords = ['信息披露', '公司治理', '业务操作', '系统填报', '政策法规', '季度报告', '股东大会']
|
||||
for kw in common_keywords:
|
||||
if keyword.lower() in kw.lower() and kw not in suggestions:
|
||||
suggestions.append(kw)
|
||||
if len(suggestions) >= 8:
|
||||
break
|
||||
|
||||
return api_response(data={'suggestions': suggestions[:8]})
|
||||
|
||||
except Exception as e:
|
||||
return api_response(success=False, error=e, status_code=500)
|
||||
|
||||
|
||||
# API路由 - QA管理
|
||||
@app.route('/api/qa')
|
||||
def get_qa_list():
|
||||
"""获取QA列表API"""
|
||||
try:
|
||||
qa_data = report_service.get_all_qa()
|
||||
# 获取查询参数
|
||||
group_id = request.args.get('group_id', '')
|
||||
keyword = request.args.get('keyword', '')
|
||||
start_time = request.args.get('start_time', '')
|
||||
end_time = request.args.get('end_time', '')
|
||||
|
||||
# 构建查询条件
|
||||
query_conditions = []
|
||||
query_params = []
|
||||
|
||||
if group_id:
|
||||
query_conditions.append("groupId LIKE ?")
|
||||
query_params.append(f"%{group_id}%")
|
||||
|
||||
if start_time and end_time:
|
||||
query_conditions.append("start_time >= ? AND end_time <= ?")
|
||||
query_params.extend([f"{start_time}000", f"{end_time}999"])
|
||||
|
||||
# 构建查询语句
|
||||
base_query = "SELECT * FROM qa"
|
||||
if query_conditions:
|
||||
base_query += " WHERE " + " AND ".join(query_conditions)
|
||||
base_query += " ORDER BY id DESC"
|
||||
|
||||
# 执行查询
|
||||
conn = db_manager.get_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(base_query, query_params)
|
||||
qa_data = cursor.fetchall()
|
||||
conn.close()
|
||||
|
||||
qa_list = [dict(qa) for qa in qa_data]
|
||||
return api_response(data={'qa_list': qa_list})
|
||||
|
||||
# 如果有关键词搜索,进行内容过滤
|
||||
if keyword:
|
||||
filtered_qa_list = []
|
||||
for qa in qa_list:
|
||||
# 检查群组ID是否匹配
|
||||
if keyword.lower() in (qa.get('groupId') or '').lower():
|
||||
filtered_qa_list.append(qa)
|
||||
continue
|
||||
|
||||
# 检查问题内容是否匹配
|
||||
try:
|
||||
question_ids = json.loads(qa.get('question', '[]'))
|
||||
if question_ids:
|
||||
# 获取问题消息内容进行匹配
|
||||
messages = report_service.get_messages_by_ids(question_ids)
|
||||
for msg in messages:
|
||||
if keyword.lower() in (msg.get('content') or '').lower():
|
||||
filtered_qa_list.append(qa)
|
||||
break
|
||||
except:
|
||||
pass
|
||||
|
||||
qa_list = filtered_qa_list
|
||||
|
||||
return api_response(data={'qa_list': qa_list, 'total': len(qa_list)})
|
||||
except Exception as e:
|
||||
return api_response(success=False, error=e, status_code=500)
|
||||
|
||||
@@ -716,14 +840,13 @@ def create_qa():
|
||||
group_id = data.get('groupId', '')
|
||||
question_ids = data.get('question', [])
|
||||
answer_ids = data.get('answer', [])
|
||||
|
||||
conn = db_manager.get_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute('''
|
||||
INSERT INTO qa (groupId, question, answer)
|
||||
VALUES (?, ?, ?)
|
||||
''', (group_id, json.dumps(question_ids), json.dumps(answer_ids)))
|
||||
INSERT INTO qa (groupId, question, answer,start_time,end_time) VALUES (?,?,?,?,?)
|
||||
''', (group_id, json.dumps(question_ids), json.dumps(answer_ids),
|
||||
data.get('start_time', ''), data.get('end_time', '')))
|
||||
|
||||
conn.commit()
|
||||
qa_id = cursor.lastrowid
|
||||
@@ -773,7 +896,7 @@ def update_qa(qa_id):
|
||||
|
||||
@app.route('/api/qa/<int:qa_id>', methods=['DELETE'])
|
||||
def delete_qa(qa_id):
|
||||
"""删除QA记录API"""
|
||||
"""删除单个QA记录API"""
|
||||
try:
|
||||
# 检查记录是否存在
|
||||
if not report_service.check_qa_exists(qa_id):
|
||||
@@ -791,9 +914,40 @@ def delete_qa(qa_id):
|
||||
except Exception as e:
|
||||
return api_response(success=False, error=e, status_code=500)
|
||||
|
||||
@app.route('/api/qa/batch', methods=['DELETE'])
|
||||
def batch_delete_qa():
|
||||
"""批量删除QA记录API"""
|
||||
try:
|
||||
data = request.get_json()
|
||||
qa_ids = data.get('qa_ids', [])
|
||||
|
||||
if not qa_ids:
|
||||
return api_response(success=False, error='请提供要删除的QA记录ID列表', status_code=400)
|
||||
|
||||
# 检查所有记录是否存在
|
||||
for qa_id in qa_ids:
|
||||
if not report_service.check_qa_exists(qa_id):
|
||||
return api_response(success=False, error=f'QA记录 {qa_id} 不存在', status_code=404)
|
||||
|
||||
conn = db_manager.get_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 构建批量删除语句
|
||||
placeholders = ','.join(['?'] * len(qa_ids))
|
||||
query = f'DELETE FROM qa WHERE id IN ({placeholders})'
|
||||
|
||||
cursor.execute(query, qa_ids)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
return api_response(status_code=404)
|
||||
|
||||
except Exception as e:
|
||||
return api_response(success=False, error=e, status_code=500)
|
||||
|
||||
|
||||
# API路由 - 报告生成
|
||||
@app.route('/api/reports/daily', defaults={'timeout': 60})
|
||||
@app.route('/api/reports/daily')
|
||||
def generate_daily_report():
|
||||
"""生成日报API"""
|
||||
try:
|
||||
@@ -877,7 +1031,7 @@ def generate_daily_report():
|
||||
|
||||
## **4. 待办事项**
|
||||
|
||||
{"有"+str(non_qa_count)+"条未被回答的问题,关注活跃群组的后续讨论,确保所有疑问被解答。" if non_qa_count > 0 else "无未被回答的问题,继续保持活跃群组的讨论。"}
|
||||
{"有" + str(non_qa_count) + "条未被回答的问题,关注活跃群组的后续讨论,确保所有疑问被解答。" if non_qa_count > 0 else "无未被回答的问题,继续保持活跃群组的讨论。"}
|
||||
|
||||
明日重点关注:根据今日热点预测明日可能的问题。
|
||||
"""
|
||||
@@ -904,7 +1058,7 @@ def generate_daily_report():
|
||||
return api_response(success=False, error=e, status_code=500)
|
||||
|
||||
|
||||
@app.route('/api/reports/weekly', defaults={'timeout': 60})
|
||||
@app.route('/api/reports/weekly')
|
||||
def generate_weekly_report():
|
||||
"""生成周报API"""
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user