-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathcore_functions.py
More file actions
2652 lines (2308 loc) · 114 KB
/
core_functions.py
File metadata and controls
2652 lines (2308 loc) · 114 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 time
import shutil
import pickle
import types
import openpyxl
import pandas as pd
import re
import hashlib
from typing import Any, Dict, List
from datetime import datetime
import gradio as gr
from loguru import logger
from utils.constants import DELIMITER, LOG_DIR
from embedding import EmbeddingModel
from utils.api_utils import vlm_generate, llm_generate, embedding_generate
from query.primitive_pipeline import *
from table2tree.feature_tree import *
from table2tree.extract_excel import process_sheet_vlm, preprocess_sheet
from config import api_config
from utils.sheet_utils import html2workbook, extract_markdown_tables
# 全局思维链条数据存储
thinking_chain_data = {}
def _normalize_artifact_prefix(name: str) -> str:
text = re.sub(r"[^a-zA-Z0-9._-]+", "_", str(name or "").strip())
text = re.sub(r"_+", "_", text).strip("._")
return text or f"table_{int(time.time())}"
def save_named_runtime_artifacts(f_tree, cache_dir, artifact_prefix):
"""Save per-file runtime artifacts: pkl/txt/embedding."""
prefix = _normalize_artifact_prefix(artifact_prefix)
tree_str = f_tree.__str__([1])
with open(os.path.join(cache_dir, f"{prefix}.pkl"), "wb") as f:
pickle.dump(f_tree, f)
with open(os.path.join(cache_dir, f"{prefix}.txt"), "w", encoding="utf-8") as f:
f.write(tree_str)
try:
raw_values = f_tree.all_value_list()
texts = [str(x) for x in raw_values] if raw_values else []
if texts:
embedding_dict = EmbeddingModel().get_embedding_dict(texts)
EmbeddingModel().save_embedding_dict(
embedding_dict, os.path.join(cache_dir, f"{prefix}.embedding.json")
)
except Exception as ee:
logger.error(f"embedding generate failed for {prefix}: {ee}")
logger.info(
f"[artifact_save] prefix={prefix}, dir={cache_dir}, "
f"files={[f'{prefix}.pkl', f'{prefix}.txt', f'{prefix}.embedding.json']}"
)
return prefix
def save_tree_artifacts(f_tree, cache_dir, source_prefix=None):
"""Save view artifacts and per-file runtime artifacts."""
tree_column_json = f_tree.__json_column__()
with open(os.path.join(cache_dir, "temp.column.json"), "w", encoding='utf-8') as f:
json.dump(tree_column_json, f, indent=4, ensure_ascii=False)
# Per-file artifacts for distinguishing multiple sources.
if source_prefix:
save_named_runtime_artifacts(f_tree, cache_dir, source_prefix)
def _safe_dom_token(value: Any) -> str:
text = str(value or "").strip()
if not text:
return "root"
text = re.sub(r"[^a-zA-Z0-9_-]+", "_", text)
text = re.sub(r"_+", "_", text).strip("_")
return text or "root"
def _build_compact_semantic_id(
legacy_semantic_id: str,
aliases: List[str],
target_kind: str = "node",
) -> str:
alias_list = [str(x or "").strip() for x in (aliases or []) if str(x or "").strip()]
first_alias = alias_list[0] if alias_list else ""
tokens: List[str] = []
if first_alias:
alias_text = first_alias
if alias_text.startswith("ft:"):
alias_text = alias_text[3:]
for seg in alias_text.split("/"):
seg = str(seg or "").strip()
if not seg:
continue
m = re.match(r"^m_\d+_(.+)$", seg)
if m:
label = _safe_dom_token(m.group(1))
if label and label not in {"ho_tree", "root"}:
tokens.append(label)
if not tokens:
tokens = ["root"]
base = "_".join(tokens[:6])
digest = hashlib.md5(str(legacy_semantic_id or "").encode("utf-8")).hexdigest()[:8]
# Keep readable path-like prefix while ensuring uniqueness by hash suffix.
return f"ct_tree_root_{base}_{digest}"
def build_and_save_tree_id_mappings(cache_dir: str, typed_root_name: str = "HO_TREE") -> Dict[str, Any]:
"""
Build stable id mappings from temp1.json/temp.column.json and save to:
- temp.id_mappings.json
"""
try:
row_path = os.path.join(cache_dir, "temp1.json")
column_path = os.path.join(cache_dir, "temp.column.json")
if not os.path.exists(row_path) or not os.path.exists(column_path):
return {}
with open(row_path, "r", encoding="utf-8") as rf:
raw_row = json.load(rf)
with open(column_path, "r", encoding="utf-8") as cf:
raw_column = json.load(cf)
if not isinstance(raw_row, dict) or not isinstance(raw_column, dict):
return {}
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,
make_canonical_trace_id,
make_tree_canonical_id,
make_tree_group_canonical_id,
)
row_alias_map = build_flat_row_alias_target_map(raw_row, typed_root_name=typed_root_name)
column_alias_map = build_flat_column_alias_target_map(raw_column, typed_root_name=typed_root_name)
semantic_bundle = build_semantic_projection_bundle(raw_row, raw_column, typed_root_name=typed_root_name)
nested_projection = build_nested_index_projection_map(
raw_column,
semantic_bundle=semantic_bundle,
typed_root_name=typed_root_name,
)
row_canonical_ids = sorted(
{
str((item or {}).get("canonical_id", "") or "").strip()
for item in (row_alias_map or {}).values()
if str((item or {}).get("canonical_id", "") or "").strip().startswith("ct_tree_")
}
)
column_canonical_ids = sorted(
{
str((item or {}).get("canonical_id", "") or "").strip()
for item in (column_alias_map or {}).values()
if str((item or {}).get("canonical_id", "") or "").strip().startswith("ct_tree_")
}
)
row_dom_map = {cid: f"row_{_safe_dom_token(cid)}" for cid in row_canonical_ids}
column_dom_map = {cid: f"column_{_safe_dom_token(cid)}" for cid in column_canonical_ids}
group_to_views: Dict[str, Dict[str, List[str]]] = {}
for alias_id, target in (row_alias_map or {}).items():
target_info = target if isinstance(target, dict) else {}
if str(target_info.get("target_kind", "") or "").strip() != "group":
continue
group_id = str(target_info.get("canonical_id", "") or "").strip()
if not group_id.startswith("ct_tree_group_"):
continue
entry = group_to_views.setdefault(group_id, {"row": [], "column": [], "aliases": []})
alias_text = str(alias_id or "").strip()
if alias_text and alias_text not in entry["aliases"]:
entry["aliases"].append(alias_text)
col_target = (column_alias_map or {}).get(alias_text, {})
if isinstance(col_target, dict):
col_cid = str(col_target.get("canonical_id", "") or "").strip()
if col_cid.startswith("ct_tree_") and col_cid not in entry["column"]:
entry["column"].append(col_cid)
def walk_row_groups(value: Any, ct_parts: List[str]) -> None:
if isinstance(value, dict):
for idx, (k, v) in enumerate(value.items()):
k_str = str(k)
cur_ct_parts = ct_parts + [f"k_{k_str}", f"idx_{idx}"]
if isinstance(v, dict):
walk_row_groups(v, cur_ct_parts + ["body"])
elif isinstance(v, list):
columns: List[Any] = []
for row in v:
if isinstance(row, dict):
for ck in row.keys():
if ck not in columns:
columns.append(ck)
for row_idx, row in enumerate(v):
if not isinstance(row, dict):
continue
row_parts = cur_ct_parts + ["body", f"i_{row_idx}", "group"]
for ck, _cv in row.items():
col_idx = columns.index(ck)
ck_str = str(ck)
group_id = make_tree_group_canonical_id(
cur_ct_parts + ["body", "header_group", f"k_{ck_str}", f"idx_{col_idx}"]
)
cell_value_id = make_tree_canonical_id(
row_parts + [f"k_{ck_str}", f"idx_{col_idx}", "body", "v"]
)
entry = group_to_views.setdefault(group_id, {"row": [], "column": [], "aliases": []})
if group_id not in entry["row"]:
entry["row"].append(group_id)
if cell_value_id not in entry["row"]:
entry["row"].append(cell_value_id)
walk_row_groups(raw_row, ["root", "flat_row", "root"])
for item in group_to_views.values():
item["row"] = sorted({str(x or "").strip() for x in item.get("row", []) if str(x or "").strip()})
item["column"] = sorted({str(x or "").strip() for x in item.get("column", []) if str(x or "").strip()})
item["aliases"] = sorted({str(x or "").strip() for x in item.get("aliases", []) if str(x or "").strip()})
semantic_to_views = (semantic_bundle or {}).get("semantic_to_views", {}) or {}
semantic_rows = (semantic_bundle or {}).get("row_canonical_to_semantic", {}) or {}
semantic_columns = (semantic_bundle or {}).get("column_canonical_to_semantic", {}) or {}
row_to_group_ids: Dict[str, List[str]] = {}
column_to_group_ids: Dict[str, List[str]] = {}
for group_id, entry in (group_to_views or {}).items():
if not isinstance(entry, dict):
continue
for row_id in (entry.get("row", []) or []):
row_text = str(row_id or "").strip()
if not row_text:
continue
row_to_group_ids.setdefault(row_text, [])
if group_id not in row_to_group_ids[row_text]:
row_to_group_ids[row_text].append(group_id)
for col_id in (entry.get("column", []) or []):
col_text = str(col_id or "").strip()
if not col_text:
continue
column_to_group_ids.setdefault(col_text, [])
if group_id not in column_to_group_ids[col_text]:
column_to_group_ids[col_text].append(group_id)
semantic_projection: Dict[str, Dict[str, Any]] = {}
semantic_compact_projection: Dict[str, Dict[str, Any]] = {}
semantic_legacy_to_compact: Dict[str, str] = {}
semantic_compact_to_legacy: Dict[str, str] = {}
semantic_legacy_to_group_ids: Dict[str, List[str]] = {}
semantic_compact_to_group_ids: Dict[str, List[str]] = {}
alias_to_semantic_compact: Dict[str, str] = {}
row_canonical_to_semantic_compact: Dict[str, str] = {}
column_canonical_to_semantic_compact: Dict[str, str] = {}
for semantic_id, payload in semantic_to_views.items():
semantic_text = str(semantic_id or "").strip()
if not semantic_text:
continue
semantic_tree_id = semantic_text.replace("ct_semantic_", "ct_tree_semantic_", 1)
row_ids = sorted(
{
str(v or "").strip()
for v in (payload.get("row", []) if isinstance(payload, dict) else [])
if str(v or "").strip()
}
)
column_ids = sorted(
{
str(v or "").strip()
for v in (payload.get("column", []) if isinstance(payload, dict) else [])
if str(v or "").strip()
}
)
alias_ids = sorted(
{
str(v or "").strip()
for v in (payload.get("aliases", []) if isinstance(payload, dict) else [])
if str(v or "").strip()
}
)
target_kind = str((payload or {}).get("target_kind", "") or "node")
group_ids = set()
for rid in row_ids:
if rid.startswith("ct_tree_group_"):
group_ids.add(rid)
for gid in row_to_group_ids.get(rid, []) or []:
group_ids.add(str(gid or "").strip())
for cid in column_ids:
for gid in column_to_group_ids.get(cid, []) or []:
group_ids.add(str(gid or "").strip())
group_ids_sorted = sorted({str(x or "").strip() for x in group_ids if str(x or "").strip()})
compact_semantic_id = _build_compact_semantic_id(
legacy_semantic_id=semantic_text,
aliases=alias_ids,
target_kind=target_kind,
)
semantic_projection[semantic_tree_id] = {
"semantic_id": semantic_text,
"target_kind": target_kind,
"row": row_ids,
"column": column_ids,
"group_ids": group_ids_sorted,
"aliases": alias_ids,
"semantic_compact_id": compact_semantic_id,
}
semantic_compact_projection[compact_semantic_id] = {
"semantic_id": semantic_text,
"target_kind": target_kind,
"row": row_ids,
"column": column_ids,
"group_ids": group_ids_sorted,
"aliases": alias_ids,
}
semantic_legacy_to_compact[semantic_text] = compact_semantic_id
semantic_compact_to_legacy[compact_semantic_id] = semantic_text
semantic_legacy_to_group_ids[semantic_text] = group_ids_sorted
semantic_compact_to_group_ids[compact_semantic_id] = group_ids_sorted
for alias_id in alias_ids:
alias_to_semantic_compact[alias_id] = compact_semantic_id
for rid in row_ids:
row_canonical_to_semantic_compact[rid] = compact_semantic_id
for cid in column_ids:
column_canonical_to_semantic_compact[cid] = compact_semantic_id
group_to_semantic_nodes: Dict[str, List[Dict[str, Any]]] = {}
semantic_to_group_ids_compact: Dict[str, List[str]] = {}
semantic_to_group_ids_legacy: Dict[str, List[str]] = {}
row_to_column_ids: Dict[str, List[str]] = {}
for compact_id, info in semantic_compact_projection.items():
if not isinstance(info, dict):
continue
legacy_id = str(info.get("semantic_id", "") or "").strip()
row_ids = [str(x or "").strip() for x in (info.get("row", []) or []) if str(x or "").strip()]
column_ids = [str(x or "").strip() for x in (info.get("column", []) or []) if str(x or "").strip()]
group_ids = [str(x or "").strip() for x in (info.get("group_ids", []) or []) if str(x or "").strip()]
semantic_to_group_ids_compact[compact_id] = sorted({g for g in group_ids})
if legacy_id:
semantic_to_group_ids_legacy[legacy_id] = sorted({g for g in group_ids})
for rid in row_ids:
row_to_column_ids.setdefault(rid, [])
for cid in column_ids:
if cid not in row_to_column_ids[rid]:
row_to_column_ids[rid].append(cid)
for gid in group_ids:
group_to_semantic_nodes.setdefault(gid, [])
group_to_semantic_nodes[gid].append({
"semantic_compact_id": compact_id,
"semantic_id": legacy_id,
"target_kind": str(info.get("target_kind", "") or "node"),
"row": row_ids,
"column": column_ids,
})
for rid, values in list(row_to_column_ids.items()):
row_to_column_ids[rid] = sorted({str(x or "").strip() for x in values if str(x or "").strip()})
for gid, items in list(group_to_semantic_nodes.items()):
uniq: Dict[str, Dict[str, Any]] = {}
for item in items:
key = str(item.get("semantic_compact_id", "") or "").strip()
if key and key not in uniq:
uniq[key] = item
group_to_semantic_nodes[gid] = [uniq[k] for k in sorted(uniq.keys())]
nested_id_projection: Dict[str, Dict[str, Any]] = {}
for semantic_id, item in (nested_projection or {}).items():
entry = item if isinstance(item, dict) else {}
path = [str(p or "").strip() for p in (entry.get("path", []) or []) if str(p or "").strip()]
nested_id = make_canonical_trace_id(["tree_nested"] + path)
nested_id_projection[nested_id] = {
"semantic_id": str(semantic_id or "").strip(),
"path": path,
"indexName": str(entry.get("indexName", "") or ""),
"drillable": bool(entry.get("drillable", False)),
"childFeaturePath": [
str(p or "").strip()
for p in (entry.get("childFeaturePath", []) or [])
if str(p or "").strip()
],
}
payload = {
"version": "v1",
"typed_root_name": typed_root_name,
"generated_at": datetime.now().isoformat(timespec="seconds"),
"row": {
"canonical_to_dom_id": row_dom_map,
"alias_to_target": row_alias_map,
},
"column": {
"canonical_to_dom_id": column_dom_map,
"alias_to_target": column_alias_map,
},
"nested": {
"ct_tree_nested_to_projection": nested_id_projection,
},
"group": {
"ct_tree_group_to_row_column": group_to_views,
},
"semantic": {
"semantic_tree_id_to_views": semantic_projection,
"semantic_compact_id_to_views": semantic_compact_projection,
"semantic_id_to_group_ids": semantic_legacy_to_group_ids,
"semantic_compact_id_to_group_ids": semantic_compact_to_group_ids,
"semantic_legacy_to_compact": semantic_legacy_to_compact,
"semantic_compact_to_legacy": semantic_compact_to_legacy,
"alias_to_semantic_compact": alias_to_semantic_compact,
"row_canonical_to_semantic": semantic_rows,
"column_canonical_to_semantic": semantic_columns,
"row_canonical_to_semantic_compact": row_canonical_to_semantic_compact,
"column_canonical_to_semantic_compact": column_canonical_to_semantic_compact,
"semantic_to_group_ids_compact": semantic_to_group_ids_compact,
"semantic_to_group_ids_legacy": semantic_to_group_ids_legacy,
"group_to_semantic_nodes": group_to_semantic_nodes,
"row_to_column_ids": row_to_column_ids,
},
}
output_path = os.path.join(cache_dir, "temp.id_mappings.json")
with open(output_path, "w", encoding="utf-8") as f:
json.dump(payload, f, ensure_ascii=False, indent=2)
try:
mapping_log_path = os.path.join(cache_dir, "temp.semantic.mapping.log.json")
mapping_log_payload = {
"generated_at": payload.get("generated_at"),
"semantic_to_group_ids_compact": payload.get("semantic", {}).get("semantic_to_group_ids_compact", {}),
"semantic_to_group_ids_legacy": payload.get("semantic", {}).get("semantic_to_group_ids_legacy", {}),
"group_to_semantic_nodes": payload.get("semantic", {}).get("group_to_semantic_nodes", {}),
"row_to_column_ids": payload.get("semantic", {}).get("row_to_column_ids", {}),
}
with open(mapping_log_path, "w", encoding="utf-8") as f:
json.dump(mapping_log_payload, f, ensure_ascii=False, indent=2)
logger.info(f"[id_mapping] semantic log saved path={mapping_log_path}")
except Exception as ee:
logger.warning(f"[id_mapping] semantic log save failed: {ee}")
logger.info(
f"[id_mapping] saved path={output_path}, "
f"row={len(row_dom_map)}, column={len(column_dom_map)}, "
f"group={len(group_to_views)}, semantic={len(semantic_projection)}, nested={len(nested_id_projection)}"
)
return payload
except Exception as e:
logger.warning(f"[id_mapping] build failed: {e}")
return {}
def _save_artifact_manifest(cache_dir, mapping):
path = os.path.join(cache_dir, "temp.artifacts.json")
with open(path, "w", encoding="utf-8") as f:
json.dump(mapping or {}, f, ensure_ascii=False, indent=2)
try:
logger.info(
f"[artifact_manifest] saved path={path}, keys={list((mapping or {}).keys())}, count={len(mapping or {})}"
)
except Exception:
pass
def _load_artifact_manifest(cache_dir):
path = os.path.join(cache_dir, "temp.artifacts.json")
if not os.path.exists(path):
logger.info(f"[artifact_manifest] not found: {path}")
return {}
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
loaded = data if isinstance(data, dict) else {}
logger.info(f"[artifact_manifest] loaded path={path}, keys={list(loaded.keys())}, count={len(loaded)}")
return loaded
except Exception as e:
logger.warning(f"[artifact_manifest] load failed path={path}: {e}")
return {}
def _choose_artifact_keys_for_query(query, manifest):
keys = [str(k) for k in (manifest or {}).keys()]
if not keys:
return []
q = str(query or "").strip().lower()
def _query_tokens(text):
text = re.sub(r"\s+", " ", str(text or "").strip().lower())
if not text:
return []
if " " in text:
return [t for t in text.split(" ") if len(t) >= 2]
# 中文/无空格场景:退化为整体 token
return [text]
q_tokens = _query_tokens(q)
key_scores = {}
for k in keys:
item = manifest.get(k, {}) if isinstance(manifest, dict) else {}
meta = item.get("meta", {}) if isinstance(item, dict) else {}
if not isinstance(meta, dict):
meta = {}
route_aliases = meta.get("route_aliases", []) if isinstance(meta.get("route_aliases", []), list) else []
header_preview = meta.get("header_preview", []) if isinstance(meta.get("header_preview", []), list) else []
index_preview = meta.get("index_preview", []) if isinstance(meta.get("index_preview", []), list) else []
display_name = str(meta.get("display_name", "") or "")
summary = str(meta.get("summary", "") or "")
candidate_texts = [k, display_name, summary] + [str(x) for x in route_aliases[:20]] + [str(x) for x in header_preview[:20]] + [str(x) for x in index_preview[:20]]
score = 0
for token in q_tokens:
for c in candidate_texts:
c_l = c.lower()
if not c_l:
continue
if token in c_l:
score += 3
elif len(token) >= 3 and c_l in token:
score += 1
# 兼容短问句:直接子串判断
q_compact = q.replace(" ", "")
for c in candidate_texts:
c_compact = str(c).lower().replace(" ", "")
if not c_compact:
continue
if q_compact and q_compact in c_compact:
score += 4
elif len(c_compact) >= 4 and c_compact in q_compact:
score += 2
key_scores[k] = score
base_rank = sorted(keys, key=lambda kk: key_scores.get(kk, 0), reverse=True)
logger.info(f"[artifact_route] lexical score={key_scores}, base_rank={base_rank}, query={query}")
# LLM hint for top-1 routing; fallback to score ranking.
llm_pick = ""
try:
candidate_lines = []
for idx, k in enumerate(base_rank, start=1):
item = manifest.get(k, {}) if isinstance(manifest, dict) else {}
meta = item.get("meta", {}) if isinstance(item, dict) else {}
if not isinstance(meta, dict):
meta = {}
summary = str(meta.get("summary", "")).strip()
display_name = str(meta.get("display_name", "")).strip()
header_preview = meta.get("header_preview", []) if isinstance(meta.get("header_preview", []), list) else []
header_preview_str = ", ".join([str(x) for x in header_preview[:10]])
value_count = meta.get("value_count", 0)
index_count = meta.get("index_count", 0)
line = (
f"{idx}. key={k} | title={display_name or 'N/A'} | summary={summary or 'N/A'} | "
f"header_preview=[{header_preview_str}] | index_count={index_count} | value_count={value_count}"
)
candidate_lines.append(line)
candidates_block = "\n".join(candidate_lines)
prompt = (
"You are selecting the most relevant table artifact for QA routing.\n"
"Do NOT rely on random key names; prioritize semantic meaning in title/summary/header_preview.\n"
"Return ONLY one key exactly as listed; no explanation.\n"
f"Question: {query}\n"
f"Candidate Keys: {base_rank}\n"
f"Candidates Detail:\n{candidates_block}\n"
)
logger.info(f"[artifact_route] llm prompt={prompt}")
llm_pick = str(get_llm_generate(prompt, max_tokens=40, temperature=0.1) or "").strip()
logger.info(f"[artifact_route] llm pick={llm_pick}")
except Exception as e:
logger.warning(f"[artifact_route] llm route hint failed: {e}")
final_rank = list(base_rank)
if llm_pick in final_rank:
final_rank.remove(llm_pick)
final_rank.insert(0, llm_pick)
logger.info(f"[artifact_route] final rank={final_rank}")
return final_rank
def _build_artifact_meta(top_key, single_tree, top_body=None):
file_key = str(top_key)
summary = {
"file_key": file_key,
"display_name": "",
"summary": "",
"route_aliases": [],
"sheet_preview": [],
"section_preview": [],
"header_preview": [],
"index_preview": [],
"index_count": 0,
"value_count": 0,
"value_preview": [],
"body_type": type(top_body).__name__,
}
random_key_like = bool(re.match(r"^tmp[a-z0-9]+$", file_key, flags=re.IGNORECASE))
try:
root_children = getattr(single_tree.index_tree.root, "children", []) or []
index_names = [str(getattr(n, "value", "")) for n in root_children]
summary["index_preview"] = index_names[:12]
summary["index_count"] = len(index_names)
except Exception:
pass
try:
values = single_tree.all_value_list() or []
summary["value_count"] = len(values)
summary["value_preview"] = [str(v) for v in values[:12]]
except Exception:
pass
# 若调用方未传 top_body,则从单树列视图反推当前文件 body。
if top_body is None:
try:
tree_column = single_tree.__json_column__()
if isinstance(tree_column, dict) and tree_column:
first_k = next(iter(tree_column.keys()))
guessed = tree_column.get(first_k)
if isinstance(guessed, (dict, list, str, int, float, bool)) or guessed is None:
top_body = guessed
summary["body_type"] = type(top_body).__name__
except Exception:
pass
# 从 canonical body 中提取更语义化的字段信息,避免只依赖 tmpxxxx key。
header_set = []
alias_set = []
sheet_set = []
section_set = []
try:
def _append_unique(bucket, text, limit=24):
t = str(text or "").strip()
if not t or t in bucket:
return
bucket.append(t)
if len(bucket) > limit:
del bucket[limit:]
# 提取 "文件 -> sheet -> 直接标题(section)" 这两层信息
if isinstance(top_body, dict):
for sheet_name, sheet_body in top_body.items():
_append_unique(sheet_set, sheet_name, limit=16)
if isinstance(sheet_body, dict):
for section_name in sheet_body.keys():
_append_unique(section_set, section_name, limit=24)
def _walk(node, depth=0):
if depth > 3:
return
if isinstance(node, dict):
for k, v in node.items():
k_text = str(k).strip()
_append_unique(header_set, k_text, limit=24)
_append_unique(alias_set, k_text, limit=24)
_walk(v, depth + 1)
elif isinstance(node, list):
for item in node[:30]:
_walk(item, depth + 1)
else:
_append_unique(alias_set, str(node), limit=24)
_walk(top_body, depth=0)
except Exception:
pass
summary["sheet_preview"] = sheet_set[:12]
summary["section_preview"] = section_set[:12]
summary["header_preview"] = header_set[:12]
display_name = ""
if summary["section_preview"]:
display_name = " / ".join(summary["section_preview"][:2])
elif summary["header_preview"]:
display_name = " / ".join(summary["header_preview"][:2])
elif summary["sheet_preview"]:
display_name = " / ".join(summary["sheet_preview"][:2])
elif summary["index_preview"]:
display_name = " / ".join(summary["index_preview"][:2])
if not display_name:
display_name = file_key
if random_key_like and summary["header_preview"]:
# 对 random key 场景,尽量显示真实表头
display_name = " / ".join(summary["header_preview"][:2])
if random_key_like and summary["section_preview"]:
display_name = " / ".join(summary["section_preview"][:2])
summary["display_name"] = display_name
route_aliases = []
for x in [display_name] + summary["sheet_preview"][:12] + summary["section_preview"][:12] + summary["header_preview"][:12] + summary["index_preview"][:12]:
t = str(x or "").strip()
if t and t not in route_aliases:
route_aliases.append(t)
summary["route_aliases"] = route_aliases[:20]
sheet_preview_text = ", ".join(summary["sheet_preview"][:4]) if summary["sheet_preview"] else ""
section_preview_text = ", ".join(summary["section_preview"][:6]) if summary["section_preview"] else ""
header_preview_text = ", ".join(summary["header_preview"][:6]) if summary["header_preview"] else ""
index_preview_text = ", ".join(summary["index_preview"][:6]) if summary["index_preview"] else ""
value_preview_text = ", ".join(summary["value_preview"][:4]) if summary["value_preview"] else ""
summary["summary"] = (
f"title={summary['display_name']}; "
f"sheets={sheet_preview_text or 'N/A'}; "
f"sections={section_preview_text or 'N/A'}; "
f"headers={header_preview_text or 'N/A'}; "
f"indexes={index_preview_text or 'N/A'}; "
f"value_count={summary['value_count']}; "
f"value_preview={value_preview_text or 'N/A'}"
)
return summary
def ensure_cache_directories(cache_dir, temp_dir=None):
"""Ensure cache directories exist"""
os.makedirs(cache_dir, exist_ok=True)
if temp_dir:
os.makedirs(temp_dir, exist_ok=True)
def handle_processing_error(e, error_prefix="处理"):
"""Standard error handling for processing functions"""
import traceback
error_msg = f"处理错误: {str(e)}\n错误详情: {traceback.format_exc()}"
gr.Warning(f"❌ {error_prefix}失败: {error_msg}")
return f"{error_prefix}失败"
def setup_cache_directory(conversation_id, default_cache_dir="cache", default_temp_dir="data/SSTQA/temp_tables"):
"""Setup cache directory based on conversation_id"""
if conversation_id:
cache_dir = os.path.join("history", conversation_id)
temp_dir = os.path.join("history", conversation_id)
else:
cache_dir = default_cache_dir
temp_dir = default_temp_dir
os.makedirs(cache_dir, exist_ok=True)
os.makedirs(temp_dir, exist_ok=True)
return cache_dir, temp_dir
def save_placeholder_data(cache_dir, placeholder_data, embedding_texts=None):
"""Save placeholder data and embeddings for conversation history"""
try:
# Save placeholder pkl file
with open(os.path.join(cache_dir, "temp.pkl"), "wb") as f:
pickle.dump(placeholder_data, f)
# Generate and save embeddings if provided
if embedding_texts:
embedding_dict = EmbeddingModel().get_embedding_dict(embedding_texts)
EmbeddingModel().save_embedding_dict(
embedding_dict, os.path.join(cache_dir, "temp.embedding.json")
)
except Exception as e:
logger.error(f"Failed to save placeholder data: {e}")
def ensure_conversation_cache(conversation_id, placeholder_data, embedding_texts=None):
"""Ensure conversation cache directory exists and save placeholder data"""
if conversation_id:
cache_dir = os.path.join("history", conversation_id)
os.makedirs(cache_dir, exist_ok=True)
save_placeholder_data(cache_dir, placeholder_data, embedding_texts)
return cache_dir
return None
def clear_directory_contents(dir_path):
"""Clear all contents from a directory, preserving the directory itself"""
if os.path.exists(dir_path):
for item in os.listdir(dir_path):
item_path = os.path.join(dir_path, item)
if os.path.isfile(item_path):
os.remove(item_path)
elif os.path.isdir(item_path):
shutil.rmtree(item_path) # 递归删除子目录
def generate_conversation_id():
"""生成唯一的对话ID,基于时间戳"""
return datetime.now().strftime("%Y%m%d_%H%M%S_%f")[:-3] # 包含毫秒以确保唯一性
def _contains_cjk(text):
return bool(re.search(r"[\u4e00-\u9fff]", text or ""))
def _truncate_title(title, max_words=8, max_chars=40):
title = (title or "").strip()
if not title:
return ""
words = title.split()
if len(words) > max_words:
title = " ".join(words[:max_words])
if len(title) > max_chars:
title = title[:max_chars].rstrip() + "..."
return title
def generate_history_title_from_questions(chat_history):
"""Generate a concise English history title from user questions."""
if not chat_history or not isinstance(chat_history, list):
return None
# 提取所有用户问题
user_questions = []
for msg in chat_history:
if isinstance(msg, dict) and msg.get("role") == "user":
question = msg.get("content", "").strip()
if question:
user_questions.append(question)
if not user_questions:
return None
# 如果只有一个问题,直接使用它;如果有多个,用LLM概括
if len(user_questions) == 1:
question_text = user_questions[0]
else:
# 合并所有问题
questions_text = "\n".join([f"{i+1}. {q}" for i, q in enumerate(user_questions)])
question_text = questions_text
# 限制问题文本长度,避免超出LLM上下文
if len(question_text) > 500:
question_text = question_text[:500] + "..."
# 使用LLM生成标题
prompt = f"""Generate a concise English title (no more than 8 words) that summarizes the core topic of the conversation.
User questions:
{question_text}
Return the title only. Do not add explanations or quotes."""
try:
title = get_llm_generate(prompt, max_tokens=50, temperature=0.3)
title = title.strip().strip('"').strip("'")
title = _truncate_title(title, max_words=8, max_chars=40)
if _contains_cjk(title):
return "Conversation Summary"
return title if title else None
except Exception as e:
logger.error(f"生成历史记录标题失败: {e}")
return None
def create_conversation_record(conversation_id, file_list, upload_time, summary, chat_history=None):
"""创建对话记录文件,用于历史记录显示
参数:
conversation_id: 对话ID
file_list: 文件列表
upload_time: 上传时间
summary: 摘要(如果提供chat_history且有用户问题,会用LLM生成标题覆盖summary)
chat_history: 对话历史,格式为[{"role": "user", "content": "问题"}, ...]
"""
history_dir = "history"
os.makedirs(history_dir, exist_ok=True)
record_file = os.path.join(history_dir, "history_records.json")
# 读取现有记录
records = []
if os.path.exists(record_file):
try:
with open(record_file, 'r', encoding='utf-8') as f:
records = json.load(f)
except:
records = []
# 如果有对话历史且有用户问题,尝试用LLM生成标题
final_summary = summary
if chat_history:
llm_title = generate_history_title_from_questions(chat_history)
if llm_title:
final_summary = llm_title
# 如果没有生成标题,使用默认summary
final_summary = _truncate_title(final_summary, max_words=8, max_chars=40) or "Conversation Summary"
# 添加新记录
new_record = {
"conversation_id": conversation_id,
"file_list": file_list,
"upload_time": upload_time,
"summary": final_summary
}
records.append(new_record)
# 保存记录
with open(record_file, 'w', encoding='utf-8') as f:
json.dump(records, f, ensure_ascii=False, indent=2)
def get_conversation_records():
"""获取所有对话记录,用于历史记录显示"""
history_dir = "history"
os.makedirs(history_dir, exist_ok=True)
record_file = os.path.join(history_dir, "history_records.json")
# 读取记录
records = []
if os.path.exists(record_file):
try:
with open(record_file, 'r', encoding='utf-8') as f:
records = json.load(f)
except:
records = []
# 转换为表格格式数据
table_data = []
for record in records:
# 将文件列表转换为字符串
file_names_str = ", ".join(record.get("file_list", []))
table_data.append([
record.get("conversation_id", ""),
file_names_str,
record.get("upload_time", ""),
record.get("summary", ""),
"查看" # 操作列
])
return table_data
def get_llm_generate(prompt, max_tokens=8192, temperature=0.5):
return llm_generate(
prompt=prompt,
key=api_config["llm_api_key"],
url=api_config["llm_api_url"],
model=api_config["llm_model"],
max_tokens=max_tokens,
temperature=temperature
)
def reshape_question_with_context(current_question, chat_history, temperature=0.5):
"""
使用上下文重塑用户问题,明确并代替可能指代不明确的代词
参数:
current_question: 当前用户问题
chat_history: 对话历史,格式为[{"role": "user", "content": "问题"}, {"role": "assistant", "content": "回答"}, ...]
temperature: LLM温度参数
返回:
重塑后的清晰问题
"""
if not chat_history or len(chat_history) == 0:
return current_question
# 构建上下文提示
context_prompt = "对话历史:\n"
for message in chat_history:
role = "用户" if message["role"] == "user" else "助手"
context_prompt += f"{role}: {message['content']}\n"
context_prompt += f"\n当前问题: {current_question}\n"
context_prompt += "\n请根据对话历史,重塑当前问题,明确并代替可能指代不明确的代词,保持问题的核心意思不变。"
context_prompt += "\n重塑后的问题:"
try:
reshaped_question = get_llm_generate(
prompt=context_prompt,
max_tokens=256,
temperature=temperature
)
logger.info(f"原始问题: {current_question}")
logger.info(f"重塑问题: {reshaped_question}")
return reshaped_question.strip()
except Exception as e:
logger.error(f"问题重塑失败: {str(e)}")
# 如果重塑失败,返回原始问题
return current_question
def get_vlm_generate():
# 返回一个已经配置好API参数的vlm_generate函数
def configured_vlm_generate(prompt, image, temperature=0.5):
return vlm_generate(
prompt=prompt,
image=image,
key=api_config["vlm_api_key"],
url=api_config["vlm_api_url"],
model=api_config["vlm_model"],
temperature=temperature
)
return configured_vlm_generate
def get_embedding_generate():
# 返回一个已经配置好API参数的embedding_generate函数
def configured_embedding_generate(input_texts, dimensions=1024):
return embedding_generate(
input_texts=input_texts,
key=api_config["embedding_api_key"],
url=api_config["embedding_api_url"],
model=api_config["embedding_model"],
dimensions=dimensions
)
return configured_embedding_generate
def convert_to_xlsx(src_path, dest_path):
"""将各种格式的文件转换为 xlsx 格式"""
ext = os.path.splitext(src_path)[1].lower()
try:
if ext == ".xlsx":
shutil.copy2(src_path, dest_path)
elif ext == ".csv":