-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathcore_functions.py
More file actions
1525 lines (1288 loc) · 63.1 KB
/
core_functions.py
File metadata and controls
1525 lines (1288 loc) · 63.1 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
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 save_tree_artifacts(f_tree, cache_dir):
"""Save all tree artifacts to the specified directory"""
tree_json = f_tree.__json__()
tree_str = f_tree.__str__([1])
with open(os.path.join(cache_dir, "temp.pkl"), "wb") as f:
pickle.dump(f_tree, f)
with open(os.path.join(cache_dir, "temp.txt"), "w", encoding='utf-8') as f:
f.write(tree_str)
with open(os.path.join(cache_dir, "temp.json"), "w", encoding='utf-8') as f:
json.dump(tree_json, f, indent=4, ensure_ascii=False)
# Generate and save embeddings
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, "temp.embedding.json")
)
except Exception as ee:
logger.error(f"embedding generate failed: {ee}")
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":
df_src = pd.read_csv(src_path)
df_src.to_excel(dest_path, index=False, engine="openpyxl")
elif ext == ".html":
html_content = open(src_path, "r", encoding="utf-8").read()
html2workbook(html_content).save(dest_path)
elif ext == ".md":
md_content = open(src_path, "r", encoding="utf-8").read()
table = extract_markdown_tables(md_content)
if table and len(table) > 1:
df_src = pd.DataFrame(table[1:], columns=table[0])
df_src.to_excel(dest_path, index=False, engine="openpyxl")
else:
shutil.copy2(src_path, dest_path)
else:
shutil.copy2(src_path, dest_path)
except Exception as e:
logger.error(f"转换文件 {src_path} 到 xlsx 失败: {e}")
shutil.copy2(src_path, dest_path)
def get_multiple_excel_feature_tree(files, log_dir=LOG_DIR, vlm_cache=False):
"""处理多个 Excel 文件,并构建成一棵总树,根节点为 'alldocument'"""
all_docs_dict = {}
temp_dir = "data/SSTQA/temp_tables"
os.makedirs(temp_dir, exist_ok=True)
for i, file_obj in enumerate(files):
# file_obj 可能是 Gradio 的 File 对象或 SimpleNamespace
src_path = file_obj.name if hasattr(file_obj, 'name') else str(file_obj)
filename = os.path.basename(src_path)
# 为每个文件创建一个唯一的临时 xlsx 名
temp_file = os.path.join(temp_dir, f"temp_{i}.xlsx")
try:
convert_to_xlsx(src_path, temp_file)
# 开启处理逻辑
wb = openpyxl.load_workbook(temp_file, data_only=True)
file_tree_dict = {}
for sheet_name in wb.sheetnames:
logger.info(f"正在处理文件 {filename} 的 Sheet: {sheet_name}")
sheet = preprocess_sheet(wb[sheet_name])
# 获取该 sheet 的结构字典 (tree_dict)
sheet_tree_dict = process_sheet_vlm(sheet, get_json=False, cache=vlm_cache)
file_tree_dict[sheet_name] = sheet_tree_dict
# 将该文件的所有 sheet 挂在文件名节点下
all_docs_dict[filename] = file_tree_dict
except Exception as e:
logger.error(f"处理文件 {filename} 失败: {e}")
continue
# 构建带 'alldocument' 根节点的字典
combined_tree_dict = {"alldocument": all_docs_dict}
# 建树并打标签
total_tree = construct_feature_tree(combined_tree_dict)
total_tree = tag_feature_tree(total_tree)
return total_tree
def process_multiple_tables_for_tree(files, conversation_id=None):
"""专门处理多个表格,生成统一的 H-OTree 结构"""
global thinking_chain_data
thinking_chain_data = {"question_answering": {}, "retrieval_chains": []}
if not files:
return None
try:
# 如果提供了 conversation_id,则创建专用文件夹,否则使用 cache 目录
if conversation_id:
cache_dir = os.path.join("history", conversation_id)
os.makedirs(cache_dir, exist_ok=True)
else:
cache_dir = "cache"
os.makedirs(cache_dir, exist_ok=True)
log_dir = LOG_DIR
# 处理表格生成总树
start_time = time.time()
f_tree = get_multiple_excel_feature_tree(files, log_dir=log_dir, vlm_cache=False)
tree_json = f_tree.__json__()
tree_str = f_tree.__str__([1])
end_time = time.time()
# 保存中间文件 (使用与单文件一致的名称,供问答逻辑使用)
save_tree_artifacts(f_tree, cache_dir)
return tree_json
except Exception as e:
import traceback
logger.error(f"多文件处理失败: {traceback.format_exc()}")
return None
def analyze_multiple_files_for_route(files):
"""分析多个文件以确定处理线路"""
if not files:
return "请选择文件"
# 分析所有文件
has_image = False
has_xlsx = False
has_text = False
file_details = []
for file in files:
file_path = file.name if hasattr(file, 'name') else file
ext = os.path.splitext(file_path)[1].lower()
if ext in [".jpg", ".jpeg", ".png", ".gif", ".bmp"]:
has_image = True
elif ext in [".xlsx", ".xls", ".docx", ".doc"]:
has_xlsx = True
else:
has_text = True # 包括 .txt, .md, .json, .csv 等
file_size = os.path.getsize(file_path)
file_details.append({
"path": file_path,
"size": file_size,
"ext": ext
})
# 按照优先级判断处理线路
# 1. 如果有任何图片文件,所有文件一起走VLM
if has_image:
return "vlm"
# 2. 如果有xlsx文件和纯文本内容,走HOTree
elif has_xlsx:
return "hotree"
# 3. 如果只有纯文本文件,走LLM
elif has_text:
return "llm"
else:
return "llm" # 默认
def determine_processing_route(file_path, file_size, file_content=None):
"""使用AI判断文件处理线路"""
if not file_path:
return "请选择文件"
# 获取文件扩展名
ext = os.path.splitext(file_path)[1].lower()
# 构建提示词
prompt = f"文件路径: {file_path}\n"
prompt += f"文件大小: {file_size} 字节\n"
prompt += f"文件类型: {ext}\n"
if file_content:
prompt += f"文件内容摘要: {file_content[:500]}...\n"
prompt += "请根据以上信息判断应该使用哪种处理线路:\n"
prompt += "1. 'llm':纯文本内容,适合使用LLM处理\n"
prompt += "2. 'vlm':包含图片或需要视觉理解的内容,适合使用VLM处理\n"
prompt += "3. 'hotree':结构化数据或表格内容,适合使用H-OTree处理\n"
prompt += "请只返回'llm'、'vlm'或'hotree'中的一个,不要添加任何其他解释。"
try:
# 调用LLM生成判断结果
result = get_llm_generate(prompt, max_tokens=10, temperature=0.1)
result = result.strip().lower()
# 验证结果有效性
if result in ["llm", "vlm", "hotree"]:
return result
else:
# 如果AI返回无效结果,使用默认规则
if ext in [".jpg", ".jpeg", ".png", ".gif", ".bmp"]:
return "vlm"
elif ext in [".xlsx", ".xls", ".docx", ".doc"]:
return "hotree"
else:
return "llm"
except Exception as e:
# 如果AI调用失败,使用默认规则
logger.error(f"AI判断线路失败: {e}")
if ext in [".jpg", ".jpeg", ".png", ".gif", ".bmp"]:
return "vlm"
elif ext in [".xlsx", ".xls", ".docx", ".doc"]:
return "hotree"
else:
return "llm"
def answer_question(
qa_pair: dict, # 一条问答对
table_file: str, # 表格原文件路径
cache_dir: str, # 存储 HO-Tree 中间结果的路径
enable_query_decompose: bool = True, # 是否启用 Query Decomposition 机制
enable_emebdding: bool = True, # 是否启用 Embedding 机制
log_dir: str = LOG_DIR, # Log 日志目录
temperature: float = 0.5, # LLM/VLM temperature
max_tokens: int = 2048 # LLM/VLM max_tokens
):
query = qa_pair["query"]
##### 创建日志文件 命名为 表格id_问题id.log
log_file = os.path.join(log_dir, f'temp.log')
log_file_handler = logger.add(
log_file,
enqueue=False, # 不使用队列,立即写入,避免缓冲
backtrace=False,
diagnose=False
)
logger.info(f"{DELIMITER} 开始问答问题 {DELIMITER}")
start_time = time.time()
logger.info(f"Question ID: temp")
logger.info(f"Table ID: temp")
logger.info(f"Question: {query}")
logger.info(f"Temperature: {temperature}")
logger.info(f"Max tokens: {max_tokens}")
##### 加载 ho_tree
pkl_file = os.path.join(cache_dir, f'temp.pkl')
embedding_cache_file = os.path.join(cache_dir, f'temp.embedding.json')
with open(pkl_file, 'rb') as file:
ho_tree = pickle.load(file)
logger.info(f"Loading PKL File: {pkl_file}")
logger.info(f"Loading Embedding Cache File: {embedding_cache_file}")
final_answer, _, reliability = qa_RWP(
query=query,
ho_tree=ho_tree,
table_file=table_file,
embedding_cache_file=embedding_cache_file,
enable_emebdding=enable_emebdding,
enable_query_decompose=enable_query_decompose,
temperature=temperature,
max_tokens=max_tokens
)
qa_pair["reliability"] = reliability
qa_pair["model_output"] = final_answer
end_time = time.time()
logger.info(f"{DELIMITER} 回答问题成功! {DELIMITER}")
logger.info(f"Cost time: {end_time - start_time}")
logger.remove(log_file_handler)
return qa_pair
def get_excel_feature_tree_multisheet(file: str, # 输入表格文件路径
log_dir: str = LOG_DIR, # LOG 日志记录路径
vlm_cache: bool = False # 是否保存转图片的中间结果
):
"""处理 Excel 文件中的所有 sheet,并构建成一棵总树"""
# 1. 打开文件获取所有 sheet
wb = openpyxl.load_workbook(file, data_only=True)
combined_tree_dict = {}
# 2. 循环处理每一个 sheet
for sheet_name in wb.sheetnames:
logger.info(f"正在处理 Sheet: {sheet_name}")
sheet = preprocess_sheet(wb[sheet_name])
# 获取该 sheet 的结构字典 (tree_dict)
sheet_tree_dict = process_sheet_vlm(sheet, get_json=False, cache=vlm_cache)
# 将每个 sheet 挂在以 sheet_name 命名的节点下
combined_tree_dict[sheet_name] = sheet_tree_dict
# 3. 传入大字典,一键生成多层级的总树
# construct_feature_tree 会递归处理字典
total_tree = construct_feature_tree(combined_tree_dict)
# 4. 递归打标签
total_tree = tag_feature_tree(total_tree)
return total_tree
def process_table_for_tree(file, conversation_id=None):
"""专门处理表格,生成H-OTree结构"""
global thinking_chain_data
# 重置思维链条数据
thinking_chain_data = {
"question_answering": {},
"retrieval_chains": []
}
if file is None:
return "请先选择表格文件", ""
# 注意:这里不再自动调用 clear_all(),由外部调用者根据需要决定
try:
# 设置缓存目录
cache_dir, temp_dir = setup_cache_directory(conversation_id, "cache", "data/SSTQA/temp_tables")
source_filename = os.path.splitext(os.path.basename(file.name))[0]
# 定义日志目录(保持在全局LOG_DIR,用于调试目的)
log_dir = LOG_DIR
# 创建临时文件
temp_file = os.path.join(temp_dir, "temp.xlsx")
# 兼容多种格式,统一转为 xlsx
src_path = file.name
ext = os.path.splitext(src_path)[1].lower()
try:
if ext == ".xlsx":
shutil.copy2(src_path, temp_file)
elif ext == ".csv":
df_src = pd.read_csv(src_path)
df_src.to_excel(temp_file, index=False, engine="openpyxl")
elif ext == ".html":
html_content = open(src_path, "r", encoding="utf-8").read()
html2workbook(html_content).save(temp_file)
elif ext == ".md":
md_content = open(src_path, "r", encoding="utf-8").read()
table = extract_markdown_tables(md_content)
with pd.ExcelWriter(temp_file, engine="openpyxl") as writer:
sheet_name = "sheet"
df_src = pd.DataFrame(table[1:], columns=table[0])
df_src.to_excel(writer, sheet_name=sheet_name, index=False)
else:
shutil.copy2(src_path, temp_file)
except Exception as e:
logger.error(f"格式转换失败: {e}")
return "文件格式不支持或转换失败", ""
# 读取表格
df = pd.read_excel(temp_file)
# 处理表格生成H-OTree
start_time = time.time()
# 使用多 Sheet 版本处理
f_tree = get_excel_feature_tree_multisheet(temp_file, log_dir=log_dir, vlm_cache=False)
tree_json = f_tree.__json__()
tree_str = f_tree.__str__([1])
end_time = time.time()
# 保存中间文件
save_tree_artifacts(f_tree, cache_dir)
# 保存额外的副本
with open(os.path.join(cache_dir, f"temp1.json"), "w", encoding='utf-8') as f:
json.dump(tree_json, f, indent=4, ensure_ascii=False)
# 这里移除 gr.Info,避免在循环处理多文件时产生大量弹窗
return tree_json
except Exception as e:
return handle_processing_error(e, "生成树")
def pure_llm_generate_answer(question, context="", temperature=0.5, max_tokens=2048):
"""Generate an answer using pure LLM."""
if not question.strip():
gr.Warning("Please enter a question")
return "Please enter a question"
try:
# 构建提示词
prompt = f"Question: {question}\n"
if context:
prompt += f"Context: {context}\n"
prompt += "Please answer the question based on the information above."
# 调用LLM生成答案
answer = get_llm_generate(prompt, max_tokens, temperature)
gr.Info("✅ LLM answer generated successfully!")
return f"Answer: {answer}"
except Exception as e:
import traceback
error_msg = f"处理错误: {str(e)}\n错误详情: {traceback.format_exc()}"
gr.Warning(f"❌ LLM answer generation failed: {error_msg}")
return "Failed to generate answer"
def pure_vlm_generate_answer(question, image_path, temperature=0.5, max_tokens=2048):
"""Generate an answer using pure VLM."""
if not question.strip():
gr.Warning("Please enter a question")
return "Please enter a question"
if not image_path:
gr.Warning("Please select an image file")
return "Please select an image file"
try:
# 构建提示词
prompt = f"Question: {question}\n"
prompt += "Please answer the question based on the image."
# 调用VLM生成答案
vlm_generate_func = get_vlm_generate()
answer = vlm_generate_func(prompt, image_path, temperature)
gr.Info("✅ VLM answer generated successfully!")
return f"Answer: {answer}"
except Exception as e:
import traceback
error_msg = f"处理错误: {str(e)}\n错误详情: {traceback.format_exc()}"
gr.Warning(f"❌ VLM answer generation failed: {error_msg}")
return "Failed to generate answer"
def process_file_with_route(file, question, temperature=0.5, max_tokens=2048, conversation_id=None):
"""根据文件类型自动选择处理线路,支持单个文件或多个文件"""
if not file:
gr.Warning("Please select a file")
return "Please select a file"
# 检查是否是多个文件
if isinstance(file, list):
return process_multiple_files_with_route(file, question, temperature, max_tokens, conversation_id=conversation_id)
else:
# 单个文件处理
try:
# 获取文件信息
file_path = file.name
file_size = os.path.getsize(file_path)
# 读取文件内容摘要
file_content = None
try:
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
file_content = f.read(1000)
except:
# 二进制文件无法读取内容
pass
# 确定处理线路
route = determine_processing_route(file_path, file_size, file_content)
# 根据线路处理文件
if route == "llm":
# 纯LLM处理
if not file_content:
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
file_content = f.read()
# 为LLM对话创建必要的处理文件,以便后续历史记录加载
if conversation_id:
placeholder_data = {
"file_type": "text",
"file_path": file_path,
"file_content_preview": file_content[:500], # 限制长度
"processing_method": "llm"
}
# 为文本内容生成嵌入向量
embedding_texts = [f"Text file: {os.path.basename(file_path)}, content: {file_content[:500]}"]
ensure_conversation_cache(conversation_id, placeholder_data, embedding_texts)
return pure_llm_generate_answer(question, file_content, temperature, max_tokens)
elif route == "vlm":
# 纯VLM处理
# 为VLM对话创建必要的处理文件,以便后续历史记录加载
if conversation_id:
placeholder_data = {
"file_type": "image",
"file_path": file_path,
"processing_method": "vlm"
}
# 为图像上下文生成简单的嵌入向量
embedding_texts = [f"Image file: {os.path.basename(file_path)}"]
ensure_conversation_cache(conversation_id, placeholder_data, embedding_texts)
return pure_vlm_generate_answer(question, file_path, temperature, max_tokens)
elif route == "hotree":
# H-OTree处理
wrapped_file = types.SimpleNamespace(name=file.name)
# process_table_for_tree会将处理结果保存到临时文件,供后续问答使用
data = process_table_for_tree(wrapped_file, conversation_id=conversation_id)
if data:
# 使用H-OTree方法回答问题
result = process_question_only(question, temperature, max_tokens, conversation_id=conversation_id)
return result
else:
return "H-OTree处理失败"
else:
return f"未知处理线路: {route}"
except Exception as e:
import traceback
error_msg = f"处理错误: {str(e)}\n错误详情: {traceback.format_exc()}"
gr.Warning(f"❌ 文件处理失败: {error_msg}")
return "文件处理失败"
def process_multiple_files_with_route(files, question, temperature=0.5, max_tokens=2048, conversation_id=None):
"""处理多个文件,根据文件类型自动选择处理线路"""
if not files or len(files) == 0:
gr.Warning("请选择文件")
return "请选择文件"
try:
# 分析多个文件以确定处理线路
route = analyze_multiple_files_for_route(files)
# 根据线路处理文件
if route == "llm":
# 纯LLM处理 - 合并所有文本文件内容
combined_content = ""
for file in files:
file_path = file.name
try:
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
content = f.read()
combined_content += f"\n--- 文件: {os.path.basename(file_path)} ---\n{content}\n"
except:
# 非文本文件跳过或简单描述
combined_content += f"\n--- 文件: {os.path.basename(file_path)} (非文本文件) ---\n"
# 为LLM对话创建必要的处理文件,以便后续历史记录加载
if conversation_id:
placeholder_data = {
"file_type": "text",
"combined_content": combined_content[:500], # 限制长度
"processing_method": "llm"
}
# 为文本内容生成嵌入向量
embedding_texts = [f"Text content: {combined_content[:500]}"]
ensure_conversation_cache(conversation_id, placeholder_data, embedding_texts)
return pure_llm_generate_answer(question, combined_content, temperature, max_tokens)
elif route == "vlm":
# VLM处理 - 优先处理图片文件,但需要考虑其他文件
# 为了更好地处理混合内容,我们先处理图片,然后将其他文件内容作为上下文
image_files = []
table_content = "" # 存储表格转换后的JSON内容
other_content = "" # 存储其他文件内容
for file in files:
file_path = file.name
ext = os.path.splitext(file_path)[1].lower()
if ext in [".jpg", ".jpeg", ".png", ".gif", ".bmp"]:
image_files.append(file_path)
elif ext in [".xlsx", ".xls", ".csv", ".docx", ".doc"]: # 表格文件
try:
# 将表格文件转换为HOTree JSON格式
wrapped_file = types.SimpleNamespace(name=file.name)
tree_json = process_table_for_tree(wrapped_file, conversation_id=conversation_id)
if tree_json:
table_content += f"\n--- 表格文件 {os.path.basename(file_path)} 的HOTree JSON结构: {json.dumps(tree_json, ensure_ascii=False, indent=2)} ---\n"
else:
# 如果转换失败,尝试作为普通文本读取
try:
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
content = f.read(1000) # 读取前1000个字符作为上下文
other_content += f"\n--- 其他文件 {os.path.basename(file_path)} 内容: {content} ---\n"
except:
other_content += f"\n--- 其他文件 {os.path.basename(file_path)} (非文本文件) ---\n"
except Exception as e:
# 如果表格转换失败,尝试作为普通文本读取
try:
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
content = f.read(1000) # 读取前1000个字符作为上下文
other_content += f"\n--- 其他文件 {os.path.basename(file_path)} 内容: {content} ---\n"
except:
other_content += f"\n--- 其他文件 {os.path.basename(file_path)} (非文本文件) ---\n"
else: # 其他类型的文件
try:
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
content = f.read(1000) # 读取前1000个字符作为上下文
other_content += f"\n--- 其他文件 {os.path.basename(file_path)} 内容: {content} ---\n"
except:
other_content += f"\n--- 其他文件 {os.path.basename(file_path)} (非文本文件) ---\n"
# 如果有图片文件,使用第一个图片文件并附加上下文
if image_files:
combined_context = ""
if table_content:
combined_context += f"表格数据: {table_content}\n"
if other_content:
combined_context += f"其他文件信息: {other_content}"
# 为VLM对话创建必要的处理文件,以便后续历史记录加载
if conversation_id:
placeholder_data = {
"file_type": "image",
"image_files": image_files,
"table_content": table_content,
"other_content": other_content,
"processing_method": "vlm"
}
# 为图像上下文生成简单的嵌入向量
context_text = f"Image files: {', '.join([os.path.basename(img) for img in image_files])}"
if table_content:
context_text += f"; Table content: {table_content[:200]}" # 限制长度
if other_content:
context_text += f"; Other content: {other_content[:200]}" # 限制长度
embedding_texts = [context_text]
ensure_conversation_cache(conversation_id, placeholder_data, embedding_texts)
if combined_context:
enhanced_question = f"{question}\n\n{combined_context}"
return pure_vlm_generate_answer(enhanced_question, image_files[0], temperature, max_tokens)
else:
return pure_vlm_generate_answer(question, image_files[0], temperature, max_tokens)
else:
# 如果没有找到图片文件但路线是VLM,使用第一个文件
# 为VLM对话创建必要的处理文件,以便后续历史记录加载
if conversation_id:
placeholder_data = {
"file_type": "image",
"file_path": files[0].name,
"processing_method": "vlm"
}
# 为图像上下文生成简单的嵌入向量
embedding_texts = [f"Image file: {os.path.basename(files[0].name)}"]
ensure_conversation_cache(conversation_id, placeholder_data, embedding_texts)
return pure_vlm_generate_answer(question, files[0].name, temperature, max_tokens)
elif route == "hotree":
# H-OTree处理 - 将所有表格文件合并为一棵树
# 过滤出所有表格文件
table_files = []
for file in files:
file_path = file.name if hasattr(file, 'name') else str(file)
ext = os.path.splitext(file_path)[1].lower()
if ext in [".xlsx", ".xls", ".csv", ".docx", ".doc"]:
table_files.append(file)
if table_files:
# --- 简化逻辑:只要有 pkl 就不重新解析 ---
# 如果提供了 conversation_id,则使用历史记录文件夹,否则使用 cache 目录
if conversation_id:
cache_dir = os.path.join("history", conversation_id)
else:
cache_dir = "cache"
cache_pkl = os.path.join(cache_dir, "temp.pkl")
if os.path.exists(cache_pkl):
logger.info("检测到本地 H-OTree 缓存,跳过解析流程。")
else:
logger.info("未检测到缓存,开始执行 H-OTree 完整解析...")
# 只有在没有缓存时才进行解析
data = process_multiple_tables_for_tree(table_files, conversation_id=conversation_id)
if not data:
return "多文件 H-OTree 解析失败"
# 使用H-OTree方法回答问题
result = process_question_only(question, temperature, max_tokens, conversation_id=conversation_id)
return result
else:
return f"未知处理线路: {route}"
except Exception as e:
import traceback
error_msg = f"处理错误: {str(e)}\n错误详情: {traceback.format_exc()}"
gr.Warning(f"❌ 多文件处理失败: {error_msg}")
return "多文件处理失败"
def process_question_only(question, temperature=0.5, max_tokens=2048, conversation_id=None):
"""专门处理问题,返回答案"""
# 如果提供了 conversation_id,则使用历史记录文件夹中的文件,否则使用默认路径