-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathweb_app.py
More file actions
3874 lines (3495 loc) · 159 KB
/
web_app.py
File metadata and controls
3874 lines (3495 loc) · 159 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
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import json
import re
import ast
import hashlib
import shutil
import sys
import asyncio
import uuid
import pickle
from datetime import datetime
import openpyxl
from fastapi import FastAPI, UploadFile, File, Form, Request
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from typing import Any, Dict, List, Optional
import uvicorn
from loguru import logger
from config import api_config, save_api_config, load_api_config
from utils.constants import LOG_DIR
# 配置日志系统,将print输出也写入日志文件
def setup_logging():
"""配置日志系统,捕获所有输出到日志文件"""
# 启动时清空日志目录
def clean_logs_on_startup():
try:
if os.path.exists(LOG_DIR):
for file in os.listdir(LOG_DIR):
if file.endswith('.log'):
file_path = os.path.join(LOG_DIR, file)
try:
os.remove(file_path)
except Exception as e:
print(f"[WARN] 无法删除日志文件 {file_path}: {e}")
except Exception as e:
print(f"[WARN] 清理日志失败: {e}")
# 清空旧日志
clean_logs_on_startup()
# 移除默认的handler(但保留一个用于控制台输出)
logger.remove()
# 添加控制台输出(带颜色,用于开发调试)
logger.add(
sys.stderr,
format="<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <level>{message}</level>",
level="INFO", # 控制台只显示INFO及以上级别
colorize=True
)
# 添加日志文件输出(所有级别,包括DEBUG)
log_file = os.path.join(LOG_DIR, "app.log")
logger.add(
log_file,
format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {message}",
level="DEBUG", # 文件记录所有级别
rotation="10 MB", # 日志文件大小超过10MB时轮转
retention="7 days", # 保留7天的日志
encoding="utf-8",
enqueue=False, # 不使用队列,立即写入,避免缓冲
backtrace=False,
diagnose=False
)
# 创建一个辅助函数,将print输出也写入日志文件
# 注意:我们不重定向全局的stdout/stderr,因为这会影响uvicorn
# 但可以通过logger.info()来记录重要信息
from core_functions import (
process_question_only,
read_all_logs,
get_thinking_chain,
process_file_with_route,
reshape_question_with_context,
save_conversation_history,
load_conversation_history,
get_conversation_records,
clear_all
)
from new_tree_ui import build_new_tree_iframe_html
from file_handlers import load_from_upload, clear_ui
from tree_handlers import persist_tree
from query.trace_builder import build_typed_trace_v2, build_trace_v3
from utils.tree_semantic_utils import (
build_flat_column_alias_target_map,
build_flat_row_alias_target_map,
build_nested_index_projection_map,
build_semantic_projection_bundle,
build_typed_body_id,
build_typed_body_segment,
build_typed_index_id,
build_typed_index_segment,
build_typed_root_parts,
build_typed_tree_v2,
make_canonical_trace_id,
)
# 初始化配置
load_api_config()
# 设置日志系统
setup_logging()
# 测试日志写入(确保日志系统正常工作)
logger.info("=" * 50)
logger.info("ST-Raptor Web应用启动")
logger.info(f"日志目录: {LOG_DIR}")
logger.info("=" * 50)
app = FastAPI(title="ST-Raptor API")
os.makedirs("history", exist_ok=True)
# CORS中间件
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 静态文件服务
if os.path.exists("static"):
app.mount("/static", StaticFiles(directory="static"), name="static")
# 图片文件服务
if os.path.exists("image"):
app.mount("/image", StaticFiles(directory="image"), name="image")
# 项目资源
if os.path.exists("assets"):
app.mount("/assets", StaticFiles(directory="assets"), name="assets")
if os.path.exists("history"):
app.mount("/history-assets", StaticFiles(directory="history"), name="history-assets")
# 根路径返回HTML
@app.get("/", response_class=HTMLResponse)
async def read_root():
html_path = os.path.join("static", "index.html")
if os.path.exists(html_path):
with open(html_path, "r", encoding="utf-8") as f:
return f.read()
return "<h1>ST-Raptor API</h1><p>请确保 static/index.html 文件存在</p>"
@app.get("/index.html", response_class=HTMLResponse)
async def project_intro():
base_index = os.path.join("index.html")
if os.path.exists(base_index):
with open(base_index, "r", encoding="utf-8") as f:
return f.read()
return "<h1>ST-Raptor Project Intro</h1><p>请确保根目录下的 index.html 存在</p>"
def _sync_tree_snapshot_for_history(conversation_id: str):
"""Best-effort sync without overriding canonical history artifacts."""
if not conversation_id:
return
history_dir = os.path.join("history", conversation_id)
os.makedirs(history_dir, exist_ok=True)
# 注意:history/<conversation_id> 下的 temp.column.json / temp1.json / temp.artifacts.json / temp.id_mappings.json
# 是该会话的 canonical 产物,不应被 cache 下的临时前端结构覆盖。
def _safe_copy_if_missing(src_name: str, dst_name: str, validator=None):
source_path = os.path.join("cache", src_name)
target_path = os.path.join(history_dir, dst_name)
if os.path.exists(target_path):
logger.info(f"[history_sync] skip existing canonical file: {target_path}")
return
if not os.path.exists(source_path):
return
if validator is not None:
try:
with open(source_path, "r", encoding="utf-8") as f:
raw = json.load(f)
if not validator(raw):
logger.warning(f"[history_sync] source shape mismatch, skip: {source_path}")
return
except Exception as e:
logger.warning(f"[history_sync] source validate failed {source_path}: {e}")
return
try:
shutil.copy2(source_path, target_path)
logger.info(f"[history_sync] copied {source_path} -> {target_path}")
except Exception as e:
logger.warning(f"[history_sync] copy failed {source_path} -> {target_path}: {e}")
_safe_copy_if_missing("temp.column.json", "temp.column.json", validator=lambda x: isinstance(x, dict))
_safe_copy_if_missing("temp1.json", "temp1.json", validator=lambda x: isinstance(x, dict))
_safe_copy_if_missing("temp.artifacts.json", "temp.artifacts.json", validator=lambda x: isinstance(x, dict))
_safe_copy_if_missing("temp.id_mappings.json", "temp.id_mappings.json", validator=lambda x: isinstance(x, dict))
def _history_tree_chat_path(conversation_id: str) -> str:
history_dir = os.path.join("history", conversation_id)
os.makedirs(history_dir, exist_ok=True)
return os.path.join(history_dir, "tree_chat.json")
def _history_images_dir(conversation_id: str) -> str:
history_dir = os.path.join("history", conversation_id)
images_dir = os.path.join(history_dir, "images")
os.makedirs(images_dir, exist_ok=True)
return images_dir
def _history_tree_images_path(conversation_id: str) -> str:
history_dir = os.path.join("history", conversation_id)
os.makedirs(history_dir, exist_ok=True)
return os.path.join(history_dir, "tree_images.json")
def _looks_like_empty_tree_payload(raw: Any) -> bool:
if raw is None:
return True
if isinstance(raw, list):
return len(raw) == 0
if isinstance(raw, dict):
return len(raw) == 0
return False
def _collect_frontend_tree_node_catalog(tree_node: Optional[Dict[str, Any]]) -> List[Dict[str, Any]]:
rows: List[Dict[str, Any]] = []
if not isinstance(tree_node, dict):
return rows
def walk(node: Dict[str, Any], parent_id: str = "", depth: int = 0) -> None:
if not isinstance(node, dict):
return
node_id = str(node.get("id", "") or "").strip()
canonical_id = str(node.get("canonicalId") or node.get("canonicalTraceId") or "").strip()
group_canonical_id = str(node.get("groupCanonicalId") or node.get("traceGroupCanonicalId") or "").strip()
rows.append({
"id": node_id,
"canonicalId": canonical_id,
"groupCanonicalId": group_canonical_id,
"parentId": str(parent_id or ""),
"nodeType": str(node.get("nodeType", "") or ""),
"sourceKind": str(node.get("sourceKind", "") or ""),
"name": str(node.get("name", "") or ""),
"depth": int(depth),
})
for child in node.get("children", []) or []:
if isinstance(child, dict):
walk(child, node_id, depth + 1)
walk(tree_node, "", 0)
return rows
def _write_debug_frontend_node_catalog(conversation_id: str, view_mode: str, tree_node: Optional[Dict[str, Any]]) -> str:
conversation_id = str(conversation_id or "").strip()
if not conversation_id or not isinstance(tree_node, dict):
return ""
try:
debug_dir = os.path.join("history", conversation_id)
os.makedirs(debug_dir, exist_ok=True)
normalized_mode = str(view_mode or "").strip().lower() or "unknown"
file_name = f"[debug]frontend.node.catalog.{normalized_mode}.json"
path = os.path.join(debug_dir, file_name)
nodes = _collect_frontend_tree_node_catalog(tree_node)
payload = {
"view_mode": normalized_mode,
"generated_at": datetime.now().isoformat(timespec="seconds"),
"root_id": str(tree_node.get("id", "") or ""),
"root_canonical_id": str(tree_node.get("canonicalId") or tree_node.get("canonicalTraceId") or ""),
"node_count": len(nodes),
"nodes": nodes,
}
with open(path, "w", encoding="utf-8") as f:
json.dump(payload, f, ensure_ascii=False, indent=2)
logger.info(
f"【debug】frontend_node_catalog saved mode={normalized_mode}, "
f"path={path}, node_count={len(nodes)}"
)
return path
except Exception as e:
logger.warning(f"【debug】frontend_node_catalog save failed mode={view_mode}: {e}")
return ""
def _build_flat_tree_node_for_view_mode(conversation_id: str, view_mode: str = "row") -> Optional[Dict[str, Any]]:
normalized_mode = str(view_mode or "").strip().lower()
if normalized_mode not in {"row", "column"}:
normalized_mode = "row"
if normalized_mode == "column":
raw_column = _load_column_view_payload(conversation_id)
if raw_column is None:
return None
return _build_flat_index_body_tree(raw_column, root_name="flat column view", path_parts=["root", "flat_column"])
raw_row = _load_row_view_payload(conversation_id)
if raw_row is None:
return None
return _build_flat_row_tree_with_trace_metadata(raw_row)
def _rebuild_history_tree_snapshot_from_files(conversation_id: str) -> bool:
"""
Rebuild history/<conversation_id>/temp.column.json and temp1.json from raw files.
"""
conversation_id = str(conversation_id or "").strip()
if not conversation_id:
return False
history_dir = os.path.join("history", conversation_id)
if not os.path.isdir(history_dir):
return False
try:
from file_handlers import merge_multiple_tables_to_tree
import types
except Exception as e:
logger.error(f"重建历史树失败(导入模块失败): {e}")
return False
candidate_files: List[Any] = []
supported_ext = {".xlsx", ".xls", ".docx", ".doc", ".txt", ".md", ".json"}
for name in os.listdir(history_dir):
full_path = os.path.join(history_dir, name)
if not os.path.isfile(full_path):
continue
ext = os.path.splitext(name)[1].lower()
if ext in supported_ext:
candidate_files.append(types.SimpleNamespace(name=full_path))
if not candidate_files:
return False
try:
merged_data, processed_files, _failed_files = merge_multiple_tables_to_tree(candidate_files, conversation_id=conversation_id)
if not processed_files:
return False
return bool(merged_data)
except Exception as e:
logger.error(f"重建历史树失败: {e}")
return False
# 获取配置
@app.get("/api/config")
async def get_config():
try:
return JSONResponse({
"success": True,
"config": api_config
})
except Exception as e:
return JSONResponse({
"success": False,
"error": str(e)
}, status_code=500)
# 保存配置
@app.post("/api/config")
async def save_config(request: Request):
try:
data = await request.json()
save_api_config(data)
return JSONResponse({
"success": True,
"message": "配置保存成功"
})
except Exception as e:
return JSONResponse({
"success": False,
"error": str(e)
}, status_code=500)
# 文件上传
@app.post("/api/upload")
async def upload_files(files: List[UploadFile] = File(...)):
try:
import tempfile
import types
# 保存上传的文件到临时目录
temp_files = []
temp_paths = []
for file in files:
# 创建临时文件
suffix = os.path.splitext(file.filename)[1]
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
temp_path = temp_file.name
temp_paths.append(temp_path)
# 写入文件内容
with open(temp_path, "wb") as f:
shutil.copyfileobj(file.file, f)
# 创建文件对象(模拟Gradio的文件对象)
file_obj = types.SimpleNamespace(name=temp_path)
temp_files.append(file_obj)
# 调用原有的上传处理函数
if len(temp_files) == 1:
result = load_from_upload(temp_files[0])
else:
result = load_from_upload(temp_files)
# 解析返回结果
tree_html, chat_messages, conversation_id = result
logger.debug(f"上传文件返回 - conversation_id: {conversation_id}")
logger.debug(f"上传文件返回 - chat_messages数量: {len(chat_messages) if chat_messages else 0}")
# 构建返回消息
message = chat_messages[0]["content"] if chat_messages else "File upload successful"
logger.debug(f"上传文件返回 - 返回的conversation_id: {conversation_id}")
_sync_tree_snapshot_for_history(conversation_id)
# 清理临时文件(延迟删除,因为可能还需要使用)
# 在实际应用中,可以设置一个清理机制
return JSONResponse({
"success": True,
"conversation_id": conversation_id,
"message": message
})
except Exception as e:
import traceback
traceback.print_exc()
return JSONResponse({
"success": False,
"error": str(e)
}, status_code=500)
# 聊天接口
def _chat_core(
message: str,
conversation_id: str = "",
temperature: float = 0.5,
max_tokens: int = 1024,
files: Optional[List[UploadFile]] = None
):
try:
logger.debug(f"/api/chat 接收 - conversation_id: '{conversation_id}', message长度: {len(message) if message else 0}")
# 获取聊天历史
chat_history = []
if conversation_id and conversation_id.strip():
try:
chat_history = load_conversation_history(conversation_id)
logger.debug(f"/api/chat 加载历史记录 - conversation_id: {conversation_id}, 消息数量: {len(chat_history)}")
except Exception as e:
logger.error(f"/api/chat 加载历史记录失败: {e}")
pass
else:
logger.warning(f"/api/chat 警告: conversation_id 为空或无效")
# 确保chat_history是有效的列表
if not isinstance(chat_history, list):
chat_history = []
# 确保用户输入不为空
if not message or message.strip() == "":
return JSONResponse({
"success": False,
"error": "Message cannot be empty"
})
try:
# 使用上下文重塑问题
reshaped_message = reshape_question_with_context(message, chat_history, temperature)
# 根据是否有文件选择处理线路
if files and len(files) > 0:
import tempfile
import types
# 保存文件到临时目录
temp_files = []
for file in files:
# 创建临时文件
suffix = os.path.splitext(file.filename)[1]
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
temp_path = temp_file.name
# 写入文件内容
with open(temp_path, "wb") as f:
shutil.copyfileobj(file.file, f)
# 创建文件对象(模拟Gradio的文件对象)
file_obj = types.SimpleNamespace(name=temp_path)
temp_files.append(file_obj)
# 有文件上传,使用process_file_with_route处理
bot_message = process_file_with_route(
temp_files[0] if len(temp_files) == 1 else temp_files,
reshaped_message,
temperature,
max_tokens,
conversation_id
)
else:
# 无文件上传,使用process_question_only处理(H-OTree线路)
bot_message = process_question_only(
reshaped_message,
temperature,
max_tokens,
conversation_id
)
# 处理返回值为空的情况
if bot_message is None or bot_message.strip() == "":
bot_message = "抱歉,未能获取到有效回答,请检查您的问题或配置。"
except Exception as e:
# 捕获异常,返回友好提示
bot_message = f"回答生成失败:{str(e)}"
# 严格按照messages格式添加消息
user_msg = {"role": "user", "content": message.strip()}
assistant_msg = {"role": "assistant", "content": bot_message.strip()}
chat_history.append(user_msg)
chat_history.append(assistant_msg)
logger.debug(f"/api/chat 准备保存 - conversation_id: '{conversation_id}', 类型: {type(conversation_id)}, 是否为空: {not conversation_id or conversation_id.strip() == ''}")
# 保存对话历史到文件
if conversation_id and conversation_id.strip():
logger.debug(f"/api/chat 保存历史记录 - conversation_id: {conversation_id}, 消息数量: {len(chat_history)}")
save_result = save_conversation_history(conversation_id, chat_history)
logger.debug(f"/api/chat 保存历史记录结果: {save_result}")
_sync_tree_snapshot_for_history(conversation_id)
# 更新历史记录标题(如果有用户问题)
try:
from core_functions import get_conversation_records, generate_history_title_from_questions
import json
# 检查是否已有记录
records = get_conversation_records()
# get_conversation_records返回的是表格格式,需要转换
record_exists = False
for r in records:
if len(r) > 0 and r[0] == conversation_id:
record_exists = True
break
if not record_exists:
# 创建新记录,使用LLM生成标题
from core_functions import create_conversation_record
from datetime import datetime
file_list = [] # 从对话历史中无法直接获取文件列表,留空
upload_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
default_summary = "New Conversation"
create_conversation_record(conversation_id, file_list, upload_time, default_summary, chat_history)
else:
# 更新现有记录的标题
llm_title = generate_history_title_from_questions(chat_history)
if llm_title:
# 更新记录
history_dir = "history"
record_file = os.path.join(history_dir, "history_records.json")
if os.path.exists(record_file):
with open(record_file, 'r', encoding='utf-8') as f:
records_data = json.load(f)
# 找到对应记录并更新
for record in records_data:
if record.get("conversation_id") == conversation_id:
record["summary"] = llm_title
break
# 保存更新后的记录
with open(record_file, 'w', encoding='utf-8') as f:
json.dump(records_data, f, ensure_ascii=False, indent=2)
except Exception as e:
logger.error(f"更新历史记录标题失败: {e}")
import traceback
logger.error(traceback.format_exc())
else:
logger.warning(f"/api/chat 警告: conversation_id 为空或无效,无法保存历史记录")
logger.warning(f"/api/chat conversation_id 值: '{conversation_id}'")
return {
"success": True,
"message": bot_message,
"conversation_id": conversation_id
}
except Exception as e:
return {
"success": False,
"error": str(e)
}
@app.post("/api/chat")
async def chat(
request: Request,
message: str = Form(...),
conversation_id: str = Form(""),
temperature: float = Form(0.5),
max_tokens: int = Form(1024),
files: Optional[List[UploadFile]] = File(None)
):
result = _chat_core(
message=message,
conversation_id=conversation_id,
temperature=temperature,
max_tokens=max_tokens,
files=files
)
if result.get("success"):
return JSONResponse(result)
return JSONResponse(result, status_code=500)
@app.post("/api/chat-stream")
async def chat_stream(
request: Request,
message: str = Form(...),
conversation_id: str = Form(""),
temperature: float = Form(0.5),
max_tokens: int = Form(1024),
files: Optional[List[UploadFile]] = File(None)
):
def _logs_html_to_lines(logs_html: str):
if not logs_html:
return []
# read_all_logs 返回的是 HTML,需要转为纯文本行
text = re.sub(r"<br\s*/?>", "\n", str(logs_html), flags=re.IGNORECASE)
text = re.sub(r"</pre>", "\n", text, flags=re.IGNORECASE)
text = re.sub(r"<[^>]+>", "", text)
return [line.strip() for line in text.split("\n") if line and line.strip()]
async def event_generator():
# 在后台线程执行耗时问答,主协程持续推送日志
chat_task = asyncio.create_task(asyncio.to_thread(
_chat_core,
message,
conversation_id,
temperature,
max_tokens,
files
))
last_lines = []
try:
while not chat_task.done():
try:
logs_html = read_all_logs(log_dir=LOG_DIR, max_lines=260)
except Exception:
logs_html = ""
current_lines = _logs_html_to_lines(logs_html)
if current_lines:
# 如果日志轮转/截断,通知前端重置
if len(current_lines) < len(last_lines) or current_lines[:len(last_lines)] != last_lines:
payload = {"type": "log_lines", "reset": True, "lines": current_lines[-120:]}
yield (json.dumps(payload, ensure_ascii=False) + "\n")
last_lines = current_lines
elif len(current_lines) > len(last_lines):
new_lines = current_lines[len(last_lines):]
payload = {"type": "log_lines", "reset": False, "lines": new_lines}
yield (json.dumps(payload, ensure_ascii=False) + "\n")
last_lines = current_lines
await asyncio.sleep(0.9)
result = await chat_task
try:
final_logs = read_all_logs(log_dir=LOG_DIR, max_lines=320)
final_lines = _logs_html_to_lines(final_logs)
if final_lines:
if len(final_lines) < len(last_lines) or final_lines[:len(last_lines)] != last_lines:
payload = {"type": "log_lines", "reset": True, "lines": final_lines[-160:]}
yield (json.dumps(payload, ensure_ascii=False) + "\n")
elif len(final_lines) > len(last_lines):
payload = {"type": "log_lines", "reset": False, "lines": final_lines[len(last_lines):]}
yield (json.dumps(payload, ensure_ascii=False) + "\n")
except Exception:
pass
done_payload = {"type": "done", **result}
yield (json.dumps(done_payload, ensure_ascii=False) + "\n")
except Exception as e:
err_payload = {"type": "done", "success": False, "error": str(e)}
yield (json.dumps(err_payload, ensure_ascii=False) + "\n")
return StreamingResponse(event_generator(), media_type="application/x-ndjson")
# 获取树视图
@app.get("/api/tree")
async def get_tree(conversation_id: str = ""):
try:
data_path = _resolve_column_view_path(conversation_id)
if conversation_id and not os.path.exists(data_path):
_rebuild_history_tree_snapshot_from_files(conversation_id)
data_path = _resolve_column_view_path(conversation_id)
trace_table_scope = ""
try:
chain_data = get_thinking_chain() or {}
qa_info = (chain_data.get("question_answering", {}) if isinstance(chain_data, dict) else {}) or {}
trace_table_scope = str(qa_info.get("table_scope", "") or "").strip()
except Exception:
trace_table_scope = ""
typed_payload = _load_typed_tree_v2_payload(conversation_id, table_scope=trace_table_scope)
if typed_payload:
html = build_new_tree_iframe_html(initial_data_path=data_path, initial_data=typed_payload)
else:
raw_column = _load_column_view_payload(conversation_id)
if raw_column is not None:
tree_node = _build_column_feature_tree_node(raw_column, ["root", "column_view"])
html = build_new_tree_iframe_html(initial_data_path=data_path, initial_data=[tree_node])
else:
html = build_new_tree_iframe_html(initial_data_path=data_path)
return JSONResponse({
"success": True,
"html": html
})
except Exception as e:
return JSONResponse({
"success": False,
"error": str(e)
}, status_code=500)
@app.get("/api/tree-column")
async def get_tree_column(conversation_id: str = ""):
# backward-compatible alias: nested view from column JSON
return await get_tree_nested(conversation_id)
@app.get("/api/tree-nested")
async def get_tree_nested(conversation_id: str = ""):
try:
raw_column = _load_column_view_payload(conversation_id)
if raw_column is None:
return JSONResponse({
"success": False,
"error": "Column view JSON not found"
}, status_code=404)
data_path = _resolve_column_view_path(conversation_id)
tree_node = _build_column_feature_tree_node(raw_column, ["root", "column_view"])
html = build_new_tree_iframe_html(initial_data_path=data_path, initial_data=[tree_node])
return JSONResponse({
"success": True,
"html": html
})
except Exception as e:
return JSONResponse({
"success": False,
"error": str(e)
}, status_code=500)
@app.get("/api/tree-nested-data")
async def get_tree_nested_data(conversation_id: str = ""):
"""
Return raw column-view JSON for custom nested renderer.
"""
try:
raw_column = _load_column_view_payload(conversation_id)
if raw_column is None:
return JSONResponse({
"success": False,
"error": "Column view JSON not found"
}, status_code=404)
return JSONResponse({
"success": True,
"data": raw_column
})
except Exception as e:
return JSONResponse({
"success": False,
"error": str(e)
}, status_code=500)
@app.get("/api/tree-flat-column")
async def get_tree_flat_column(conversation_id: str = ""):
try:
raw_column = _load_column_view_payload(conversation_id)
if raw_column is None:
return JSONResponse({
"success": False,
"error": "Column view JSON not found"
}, status_code=404)
data_path = _resolve_column_view_path(conversation_id)
tree_node = _build_flat_index_body_tree(raw_column, root_name="flat column view", path_parts=["root", "flat_column"])
debug_catalog_path = _write_debug_frontend_node_catalog(conversation_id, "column", tree_node)
html = build_new_tree_iframe_html(initial_data_path=data_path, initial_data=[tree_node])
return JSONResponse({
"success": True,
"html": html,
"debug_frontend_node_catalog": debug_catalog_path,
})
except Exception as e:
return JSONResponse({
"success": False,
"error": str(e)
}, status_code=500)
@app.get("/api/tree-flat-row")
async def get_tree_flat_row(conversation_id: str = ""):
try:
raw_row = _load_row_view_payload(conversation_id)
if raw_row is None:
return JSONResponse({
"success": False,
"error": "Row view JSON not found"
}, status_code=404)
data_path = _resolve_row_view_path(conversation_id)
tree_node = _build_flat_row_tree_with_trace_metadata(raw_row)
debug_catalog_path = _write_debug_frontend_node_catalog(conversation_id, "row", tree_node)
html = build_new_tree_iframe_html(initial_data_path=data_path, initial_data=[tree_node])
return JSONResponse({
"success": True,
"html": html,
"debug_frontend_node_catalog": debug_catalog_path,
})
except Exception as e:
return JSONResponse({
"success": False,
"error": str(e)
}, status_code=500)
# 获取日志
@app.get("/api/logs")
async def get_logs():
try:
import os
# 调试:检查日志目录和文件
log_files = []
if os.path.exists(LOG_DIR):
log_files = [f for f in os.listdir(LOG_DIR) if f.endswith('.log')]
# 不再记录这些定期显示的调试信息,减少日志噪音
# logger.debug(f"日志目录: {LOG_DIR}, 日志文件数量: {len(log_files)}, 文件列表: {log_files}")
logs = read_all_logs(log_dir=LOG_DIR, max_lines=200)
# logger.debug(f"读取日志结果长度: {len(logs) if logs else 0}")
return JSONResponse({
"success": True,
"logs": logs
})
except Exception as e:
import traceback
traceback.print_exc()
return JSONResponse({
"success": False,
"error": str(e)
}, status_code=500)
def _normalize_text_for_trace(text: Any) -> str:
return re.sub(r"\s+", "", str(text or "").lower()).strip()
def _make_trace_node_id(path_parts: List[str]) -> str:
raw = "|".join(path_parts) if path_parts else "root"
safe = re.sub(r"[^a-zA-Z0-9_-]+", "_", raw)
safe = re.sub(r"_+", "_", safe).strip("_")
return f"n_{safe or 'root'}"
def _make_tree_canonical_id(path_parts: List[str]) -> str:
return make_canonical_trace_id(["tree"] + list(path_parts or []))
def _make_tree_group_canonical_id(path_parts: List[str]) -> str:
return make_canonical_trace_id(["tree_group"] + list(path_parts or []))
def _append_trace_alias(node: Dict[str, Any], alias: Any) -> None:
text = str(alias or "").strip()
if not text:
return
aliases = node.setdefault("traceAliases", [])
if text not in aliases:
aliases.append(text)
def _get_node_canonical_id(node: Dict[str, Any]) -> str:
if not isinstance(node, dict):
return ""
return str(node.get("canonicalId") or node.get("canonicalTraceId") or "").strip()
def _get_node_group_canonical_id(node: Dict[str, Any]) -> str:
if not isinstance(node, dict):
return ""
return str(node.get("groupCanonicalId") or node.get("traceGroupCanonicalId") or "").strip()
def _infer_trace_target_kind(canonical_id: Any) -> str:
text = str(canonical_id or "").strip()
if not text:
return ""
if text.startswith("ct_tree_group_") or text.startswith("ct_semantic_group_"):
return "group"
return "node"
def _sync_tree_trace_identity_fields(tree_node: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
if not isinstance(tree_node, dict):
return tree_node
def sync(node: Dict[str, Any]) -> None:
canonical_id = _get_node_canonical_id(node)
group_canonical_id = _get_node_group_canonical_id(node)
if canonical_id:
node["canonicalId"] = canonical_id
node["canonicalTraceId"] = canonical_id
if group_canonical_id:
node["groupCanonicalId"] = group_canonical_id
node["traceGroupCanonicalId"] = group_canonical_id
_walk_tree_nodes(tree_node, sync)
return tree_node
def _compute_tree_trace_fingerprint(tree_node: Optional[Dict[str, Any]]) -> str:
if not isinstance(tree_node, dict):
return ""
records: List[Dict[str, str]] = []
def walk(node: Dict[str, Any], parent_canonical_id: str = "") -> None:
canonical_id = _get_node_canonical_id(node)
group_canonical_id = _get_node_group_canonical_id(node)
if canonical_id or group_canonical_id:
records.append({
"canonical_id": canonical_id,
"group_canonical_id": group_canonical_id,
"parent_canonical_id": str(parent_canonical_id or ""),
"node_type": str(node.get("nodeType", "") or ""),
})
next_parent = canonical_id or parent_canonical_id
for child in node.get("children", []) or []:
if isinstance(child, dict):
walk(child, next_parent)
walk(tree_node, "")
if not records:
return ""
records.sort(
key=lambda item: (
str(item.get("canonical_id", "") or ""),
str(item.get("group_canonical_id", "") or ""),
str(item.get("parent_canonical_id", "") or ""),
str(item.get("node_type", "") or ""),
)
)
payload = json.dumps(records, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
digest = hashlib.sha256(payload.encode("utf-8")).hexdigest()[:24]
return f"tf_{digest}"
def _walk_tree_nodes(node: Any, visit) -> None:
if not isinstance(node, dict):
return
visit(node)
for child in node.get("children", []) or []:
_walk_tree_nodes(child, visit)
def _index_tree_nodes_by_canonical(tree_node: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
mapping: Dict[str, Dict[str, Any]] = {}
def collect(node: Dict[str, Any]) -> None:
canonical_id = _get_node_canonical_id(node)
if canonical_id:
mapping[canonical_id] = node
_walk_tree_nodes(tree_node, collect)
return mapping
def _build_trace_alias_target_map(tree_node: Optional[Dict[str, Any]]) -> Dict[str, Dict[str, str]]:
alias_hits: Dict[str, List[Dict[str, str]]] = {}
if not isinstance(tree_node, dict):
return {}
def collect(node: Dict[str, Any]) -> None:
canonical_id = _get_node_canonical_id(node)
group_canonical_id = _get_node_group_canonical_id(node)
if not canonical_id and not group_canonical_id:
return
for alias in node.get("traceAliases", []) or []:
alias_text = str(alias or "").strip()
if not alias_text:
continue
alias_hits.setdefault(alias_text, []).append({
"canonical": canonical_id,
"group": group_canonical_id,
})
_walk_tree_nodes(tree_node, collect)
resolved: Dict[str, Dict[str, str]] = {}
for alias, hits in alias_hits.items():
concrete = sorted({str(hit.get("canonical", "") or "").strip() for hit in hits if str(hit.get("canonical", "") or "").strip()})
groups = sorted({str(hit.get("group", "") or "").strip() for hit in hits if str(hit.get("group", "") or "").strip()})
if len(concrete) == 1:
resolved[alias] = {
"canonical_id": concrete[0],
"target_kind": "node",
}
continue
if len(groups) == 1: