from typing import Any, Dict, List import gradio as gr import json import re from difflib import SequenceMatcher from scripts.main import main, feedback import os from utils import count_tokens current_dir = os.path.dirname(os.path.abspath(__file__)) output_path = os.path.join(current_dir, "output.json") converted_path = os.path.join(current_dir, "converted") def extract_sequence_from_id(chunk_id: str) -> int: """Trích xuất sequence number từ chunk ID""" # Format: doc_id::CH7::A18::K4::P0::C63 match = re.search(r'::C(\d+)$', chunk_id) if match: return int(match.group(1)) return 0 def load_document_chunks(doc_id: str) -> List[Dict]: """Load tất cả chunks của một document và sắp xếp theo thứ tự""" import os current_dir = os.path.dirname(os.path.abspath(__file__)) chunks_path = os.path.join(current_dir, "chunks") manifest_path = os.path.join(chunks_path, "chunks_manifest.json") if not os.path.exists(manifest_path): return [] with open(manifest_path, "r", encoding="utf-8") as f: manifest = json.load(f) # Lọc chunks của document này doc_chunks = [] for chunk_info in manifest["chunks"]: if chunk_info["id"].startswith(doc_id): chunk_file_path = chunk_info["path"] if os.path.exists(chunk_file_path): with open(chunk_file_path, "r", encoding="utf-8") as f: chunk_data = json.load(f) doc_chunks.append(chunk_data) # Sắp xếp theo sequence number doc_chunks.sort(key=lambda x: extract_sequence_from_id(x["id"])) return doc_chunks def reconstruct_document(chunks: List[Dict]) -> str: """Tái tạo lại document từ các chunks""" if not chunks: return "" document_parts = [] current_path = [] for chunk in chunks: content_type = chunk.get("content_type", "text") chunk_text = chunk.get("chunk_text", "") path = chunk.get("path", []) # Thêm headers từ path nếu có thay đổi if path != current_path: # Tìm phần tử mới trong path for i, path_item in enumerate(path): if i >= len(current_path) or path_item != current_path[i]: # Thêm header mới if path_item and path_item not in ["ROOT", "TABLE"]: # Xác định level dựa trên vị trí trong path level = i + 1 # Đặc biệt xử lý cho "Điểm" - sử dụng level 4 (####) if "Điểm" in path_item: header_marker = "####" else: header_marker = "#" * min(level, 6) # Tối đa 6 dấu # document_parts.append(f"\n{header_marker} {path_item}\n") break current_path = path if content_type == "table": # Thêm table với định dạng markdown document_parts.append(f"\n{chunk_text}\n") else: # Thêm text thông thường, bao gồm cả markdown headings if chunk_text.strip(): document_parts.append(chunk_text) return "\n".join(document_parts) def find_text_positions_in_reconstructed_doc(text_to_find: str, reconstructed_doc: str) -> List[tuple]: """Tìm tất cả vị trí của text trong document đã tái tạo""" positions = [] start = 0 while True: pos = reconstructed_doc.find(text_to_find, start) if pos == -1: break positions.append((pos, pos + len(text_to_find))) start = pos + 1 return positions def highlight_text_in_reconstructed_doc(texts_to_highlight: List[str], reconstructed_doc: str, chunks: List[Dict] = None) -> str: """Highlight text trong document đã tái tạo""" if not texts_to_highlight: return reconstructed_doc # Tạo bản sao để highlight highlighted_doc = reconstructed_doc # Sắp xếp texts theo độ dài (dài trước) để tránh highlight overlap sorted_texts = sorted(texts_to_highlight, key=len, reverse=True) for i, text in enumerate(sorted_texts): if not text.strip(): continue # Tìm vị trí của text trong document đã tái tạo positions = find_text_positions_in_reconstructed_doc(text, highlighted_doc) # Nếu không tìm thấy trong document đã tái tạo và có chunks, tìm trong chunk_for_embedding if not positions and chunks: for chunk in chunks: chunk_embedding = chunk.get('chunk_for_embedding', '') if text in chunk_embedding: # Thêm text vào document để highlight highlighted_doc += f"\n\n{text}" positions = [(len(highlighted_doc) - len(text), len(highlighted_doc))] break # Highlight từ cuối lên để không ảnh hưởng đến vị trí của các text khác for start, end in reversed(positions): token_count = count_tokens(text) highlighted_text = f'{text} ({token_count} tokens)' highlighted_doc = highlighted_doc[:start] + highlighted_text + highlighted_doc[end:] return highlighted_doc def format_highlighted_doc(highlighted_doc: str) -> str: """Format highlighted doc to be more readable""" # Convert markdown headings to HTML headings import re # Convert # to h1, ## to h2, ### to h3, #### to h4 # Handle both with and without leading spaces formatted_doc = re.sub(r'^\s*# (.+)$', r'
Document ID: {doc_id}
Actually highlighted: {highlighted_count}
Success rate: {success_rate:.1f}%
{format_highlighted_doc(highlighted_doc)}"
def format_user_prompt(user_prompt: str) -> str:
"""Format user prompt to be more readable"""
# Make "Chunk" bold using HTML
token_count = count_tokens(user_prompt)
formatted_prompt = user_prompt.replace("Chunk", "Chunk")
# Convert newlines to Total tokens: {token_count}