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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dotenv import load_dotenv
|
| 3 |
+
load_dotenv()
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import pandas as pd
|
| 7 |
+
|
| 8 |
+
import zipfile
|
| 9 |
+
import xml.etree.ElementTree as ET
|
| 10 |
+
from io import BytesIO
|
| 11 |
+
import openpyxl
|
| 12 |
+
|
| 13 |
+
from openai import OpenAI
|
| 14 |
+
|
| 15 |
+
import re
|
| 16 |
+
|
| 17 |
+
import logging
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
HF_API_KEY = os.getenv("HF_API_KEY")
|
| 21 |
+
|
| 22 |
+
# Configure logging to write to 'zaoju_logs.log' without using pickle
|
| 23 |
+
logging.basicConfig(
|
| 24 |
+
filename='extract_po_logs.log',
|
| 25 |
+
level=logging.INFO,
|
| 26 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
| 27 |
+
encoding='utf-8'
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
# Default Word XML namespace
|
| 31 |
+
DEFAULT_NS = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
|
| 32 |
+
NS = None # Global variable to store the namespace
|
| 33 |
+
|
| 34 |
+
def get_namespace(root):
|
| 35 |
+
"""Extracts the primary namespace from the XML root element while keeping the default."""
|
| 36 |
+
global NS
|
| 37 |
+
|
| 38 |
+
ns = root.tag.split('}')[0].strip('{')
|
| 39 |
+
NS = {'w': ns} if ns else DEFAULT_NS
|
| 40 |
+
|
| 41 |
+
return NS
|
| 42 |
+
|
| 43 |
+
# --- Helper Functions for DOCX Processing ---
|
| 44 |
+
|
| 45 |
+
def extract_text_from_cell(cell):
|
| 46 |
+
"""Extracts text from a Word table cell, preserving line breaks and reconstructing split words."""
|
| 47 |
+
paragraphs = cell.findall('.//w:p', NS)
|
| 48 |
+
lines = []
|
| 49 |
+
|
| 50 |
+
for paragraph in paragraphs:
|
| 51 |
+
# Get all text runs and concatenate their contents
|
| 52 |
+
text_runs = [t.text for t in paragraph.findall('.//w:t', NS) if t.text]
|
| 53 |
+
line = ''.join(text_runs).strip() # Merge split words properly
|
| 54 |
+
|
| 55 |
+
if line: # Add only non-empty lines
|
| 56 |
+
lines.append(line)
|
| 57 |
+
|
| 58 |
+
return lines # Return list of lines to preserve line breaks
|
| 59 |
+
|
| 60 |
+
def clean_spaces(text):
|
| 61 |
+
"""
|
| 62 |
+
Removes excessive spaces between Chinese characters while preserving spaces in English words.
|
| 63 |
+
"""
|
| 64 |
+
# Remove spaces **between** Chinese characters but keep English spaces
|
| 65 |
+
text = re.sub(r'([\u4e00-\u9fff])\s+([\u4e00-\u9fff])', r'\1\2', text)
|
| 66 |
+
return text.strip()
|
| 67 |
+
|
| 68 |
+
def extract_key_value_pairs(text, target_dict=None):
|
| 69 |
+
"""
|
| 70 |
+
Extracts multiple key-value pairs from a given text.
|
| 71 |
+
- First, split by more than 3 spaces (`\s{3,}`) **only if the next segment contains a `:`.**
|
| 72 |
+
- Then, process each segment by splitting at `:` to correctly assign keys and values.
|
| 73 |
+
"""
|
| 74 |
+
if target_dict is None:
|
| 75 |
+
target_dict = {}
|
| 76 |
+
|
| 77 |
+
text = text.replace(":", ":") # Normalize Chinese colons to English colons
|
| 78 |
+
|
| 79 |
+
# Step 1: Check if splitting by more than 3 spaces is necessary
|
| 80 |
+
segments = re.split(r'(\s{3,})', text) # Use raw string to prevent invalid escape sequence
|
| 81 |
+
|
| 82 |
+
# Step 2: Process each segment, ensuring we only split if the next part has a `:`
|
| 83 |
+
merged_segments = []
|
| 84 |
+
temp_segment = ""
|
| 85 |
+
|
| 86 |
+
for segment in segments:
|
| 87 |
+
if ":" in segment: # If segment contains `:`, it's a valid split point
|
| 88 |
+
if temp_segment:
|
| 89 |
+
merged_segments.append(temp_segment.strip())
|
| 90 |
+
temp_segment = ""
|
| 91 |
+
merged_segments.append(segment.strip())
|
| 92 |
+
else:
|
| 93 |
+
temp_segment += " " + segment.strip()
|
| 94 |
+
|
| 95 |
+
if temp_segment:
|
| 96 |
+
merged_segments.append(temp_segment.strip())
|
| 97 |
+
|
| 98 |
+
# Step 3: Extract key-value pairs correctly
|
| 99 |
+
for segment in merged_segments:
|
| 100 |
+
if ':' in segment:
|
| 101 |
+
key, value = segment.split(':', 1) # Only split at the first colon
|
| 102 |
+
key, value = key.strip(), value.strip() # Clean spaces
|
| 103 |
+
|
| 104 |
+
if key in target_dict:
|
| 105 |
+
target_dict[key] += "\n" + value # Append if key already exists
|
| 106 |
+
else:
|
| 107 |
+
target_dict[key] = value
|
| 108 |
+
|
| 109 |
+
return target_dict
|
| 110 |
+
|
| 111 |
+
# --- Table Processing Functions ---
|
| 112 |
+
|
| 113 |
+
def process_single_column_table(rows):
|
| 114 |
+
"""Processes a single-column table and returns the extracted lines as a list."""
|
| 115 |
+
single_column_data = []
|
| 116 |
+
|
| 117 |
+
for row in rows:
|
| 118 |
+
cells = row.findall('.//w:tc', NS)
|
| 119 |
+
if len(cells) == 1:
|
| 120 |
+
cell_lines = extract_text_from_cell(cells[0]) # Extract all lines from the cell
|
| 121 |
+
|
| 122 |
+
# Append each line directly to the list without splitting
|
| 123 |
+
single_column_data.extend(cell_lines)
|
| 124 |
+
|
| 125 |
+
return single_column_data # Return the list of extracted lines
|
| 126 |
+
|
| 127 |
+
def process_buyer_seller_table(rows):
|
| 128 |
+
"""Processes a two-column buyer-seller table into a structured dictionary using the first row as keys."""
|
| 129 |
+
headers = [extract_text_from_cell(cell) for cell in rows[0].findall('.//w:tc', NS)]
|
| 130 |
+
if len(headers) != 2:
|
| 131 |
+
return None # Not a buyer-seller table
|
| 132 |
+
|
| 133 |
+
# determine role based on header text
|
| 134 |
+
def get_role(header_text, default_role):
|
| 135 |
+
header_text = header_text.lower() # Convert to lowercase
|
| 136 |
+
if '买方' in header_text or 'buyer' in header_text or '甲方' in header_text:
|
| 137 |
+
return 'buyer_info'
|
| 138 |
+
elif '卖方' in header_text or 'seller' in header_text or '乙方' in header_text:
|
| 139 |
+
return 'seller_info'
|
| 140 |
+
else:
|
| 141 |
+
return default_role # Default if no keyword is found
|
| 142 |
+
|
| 143 |
+
# Determine the keys for buyer and seller columns
|
| 144 |
+
buyer_key = get_role(headers[0][0], 'buyer_info')
|
| 145 |
+
seller_key = get_role(headers[1][0], 'seller_info')
|
| 146 |
+
|
| 147 |
+
# Initialize the dictionary using the determined keys
|
| 148 |
+
buyer_seller_data = {
|
| 149 |
+
buyer_key: {},
|
| 150 |
+
seller_key: {}
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
for row in rows:
|
| 154 |
+
cells = row.findall('.//w:tc', NS)
|
| 155 |
+
if len(cells) == 2:
|
| 156 |
+
buyer_lines = extract_text_from_cell(cells[0])
|
| 157 |
+
seller_lines = extract_text_from_cell(cells[1])
|
| 158 |
+
|
| 159 |
+
for line in buyer_lines:
|
| 160 |
+
extract_key_value_pairs(line, buyer_seller_data[buyer_key])
|
| 161 |
+
|
| 162 |
+
for line in seller_lines:
|
| 163 |
+
extract_key_value_pairs(line, buyer_seller_data[seller_key])
|
| 164 |
+
|
| 165 |
+
return buyer_seller_data
|
| 166 |
+
|
| 167 |
+
def process_summary_table(rows):
|
| 168 |
+
"""Processes a two-column summary table where keys are extracted as dictionary keys."""
|
| 169 |
+
extracted_data = []
|
| 170 |
+
|
| 171 |
+
for row in rows:
|
| 172 |
+
cells = row.findall('.//w:tc', NS)
|
| 173 |
+
if len(cells) == 2:
|
| 174 |
+
key = " ".join(extract_text_from_cell(cells[0]))
|
| 175 |
+
value = " ".join(extract_text_from_cell(cells[1]))
|
| 176 |
+
extracted_data.append({key: value})
|
| 177 |
+
|
| 178 |
+
return extracted_data
|
| 179 |
+
|
| 180 |
+
def extract_headers(first_row_cells):
|
| 181 |
+
"""Extracts unique column headers from the first row of a table."""
|
| 182 |
+
headers = []
|
| 183 |
+
header_count = {}
|
| 184 |
+
for cell in first_row_cells:
|
| 185 |
+
cell_text = " ".join(extract_text_from_cell(cell))
|
| 186 |
+
grid_span = cell.find('.//w:gridSpan', NS)
|
| 187 |
+
col_span = int(grid_span.attrib.get(f'{{{NS["w"]}}}val', '1')) if grid_span is not None else 1
|
| 188 |
+
for _ in range(col_span):
|
| 189 |
+
# Ensure header uniqueness by appending an index if repeated
|
| 190 |
+
if cell_text in header_count:
|
| 191 |
+
header_count[cell_text] += 1
|
| 192 |
+
unique_header = f"{cell_text}_{header_count[cell_text]}"
|
| 193 |
+
else:
|
| 194 |
+
header_count[cell_text] = 1
|
| 195 |
+
unique_header = cell_text
|
| 196 |
+
headers.append(unique_header if unique_header else f"Column_{len(headers) + 1}")
|
| 197 |
+
return headers
|
| 198 |
+
|
| 199 |
+
def process_long_table(rows):
|
| 200 |
+
"""Processes a standard table and correctly handles horizontally merged cells."""
|
| 201 |
+
if not rows:
|
| 202 |
+
return [] # Avoid IndexError
|
| 203 |
+
|
| 204 |
+
headers = extract_headers(rows[0].findall('.//w:tc', NS))
|
| 205 |
+
table_data = []
|
| 206 |
+
vertical_merge_tracker = {}
|
| 207 |
+
|
| 208 |
+
for row in rows[1:]:
|
| 209 |
+
row_data = {}
|
| 210 |
+
cells = row.findall('.//w:tc', NS)
|
| 211 |
+
running_index = 0
|
| 212 |
+
|
| 213 |
+
for cell in cells:
|
| 214 |
+
cell_text = " ".join(extract_text_from_cell(cell))
|
| 215 |
+
|
| 216 |
+
# Consistent Namespace Handling for Horizontal Merge
|
| 217 |
+
grid_span = cell.find('.//w:gridSpan', NS)
|
| 218 |
+
grid_span_val = grid_span.attrib.get(f'{{{NS["w"]}}}val') if grid_span is not None else '1'
|
| 219 |
+
col_span = int(grid_span_val)
|
| 220 |
+
|
| 221 |
+
# Handle vertical merge
|
| 222 |
+
v_merge = cell.find('.//w:vMerge', NS)
|
| 223 |
+
if v_merge is not None:
|
| 224 |
+
v_merge_val = v_merge.attrib.get(f'{{{NS["w"]}}}val')
|
| 225 |
+
if v_merge_val == 'restart':
|
| 226 |
+
vertical_merge_tracker[running_index] = cell_text
|
| 227 |
+
else:
|
| 228 |
+
# Repeat the value from the previous row's merged cell
|
| 229 |
+
cell_text = vertical_merge_tracker.get(running_index, "")
|
| 230 |
+
|
| 231 |
+
# Repeat the value for horizontally merged cells
|
| 232 |
+
start_col = running_index
|
| 233 |
+
end_col = running_index + col_span
|
| 234 |
+
|
| 235 |
+
# Repeat the value for each spanned column
|
| 236 |
+
for col in range(start_col, end_col):
|
| 237 |
+
key = headers[col] if col < len(headers) else f"Column_{col+1}"
|
| 238 |
+
row_data[key] = cell_text
|
| 239 |
+
|
| 240 |
+
# Update the running index to the end of the merged cell
|
| 241 |
+
running_index = end_col
|
| 242 |
+
|
| 243 |
+
# Fill remaining columns with empty strings to maintain alignment
|
| 244 |
+
while running_index < len(headers):
|
| 245 |
+
row_data[headers[running_index]] = ""
|
| 246 |
+
running_index += 1
|
| 247 |
+
|
| 248 |
+
table_data.append(row_data)
|
| 249 |
+
|
| 250 |
+
return table_data
|
| 251 |
+
|
| 252 |
+
def extract_tables(root):
|
| 253 |
+
"""Extracts tables from the DOCX document and returns structured data."""
|
| 254 |
+
tables = root.findall('.//w:tbl', NS)
|
| 255 |
+
table_data = {}
|
| 256 |
+
table_paragraphs = set()
|
| 257 |
+
|
| 258 |
+
for table_index, table in enumerate(tables, start=1):
|
| 259 |
+
rows = table.findall('.//w:tr', NS)
|
| 260 |
+
if not rows:
|
| 261 |
+
continue # Skip empty tables
|
| 262 |
+
|
| 263 |
+
for paragraph in table.findall('.//w:p', NS):
|
| 264 |
+
table_paragraphs.add(paragraph)
|
| 265 |
+
|
| 266 |
+
first_row_cells = rows[0].findall('.//w:tc', NS)
|
| 267 |
+
num_columns = len(first_row_cells)
|
| 268 |
+
|
| 269 |
+
if num_columns == 1:
|
| 270 |
+
single_column_data = process_single_column_table(rows)
|
| 271 |
+
if single_column_data:
|
| 272 |
+
table_data[f"table_{table_index}_single_column"] = single_column_data
|
| 273 |
+
continue # Skip further processing for this table
|
| 274 |
+
|
| 275 |
+
summary_start_index = None
|
| 276 |
+
for i, row in enumerate(rows):
|
| 277 |
+
if len(row.findall('.//w:tc', NS)) == 2:
|
| 278 |
+
summary_start_index = i
|
| 279 |
+
break
|
| 280 |
+
|
| 281 |
+
long_table_data = []
|
| 282 |
+
summary_data = []
|
| 283 |
+
|
| 284 |
+
if summary_start_index is not None and summary_start_index > 0:
|
| 285 |
+
long_table_data = process_long_table(rows[:summary_start_index])
|
| 286 |
+
elif summary_start_index is None:
|
| 287 |
+
long_table_data = process_long_table(rows)
|
| 288 |
+
|
| 289 |
+
if summary_start_index is not None:
|
| 290 |
+
is_buyer_seller_table = all(len(row.findall('.//w:tc', NS)) == 2 for row in rows)
|
| 291 |
+
if is_buyer_seller_table:
|
| 292 |
+
buyer_seller_data = process_buyer_seller_table(rows)
|
| 293 |
+
if buyer_seller_data:
|
| 294 |
+
table_data[f"table_{table_index}_buyer_seller"] = buyer_seller_data
|
| 295 |
+
else:
|
| 296 |
+
summary_data = process_summary_table(rows[summary_start_index:])
|
| 297 |
+
|
| 298 |
+
if long_table_data:
|
| 299 |
+
table_data[f"long_table_{table_index}"] = long_table_data
|
| 300 |
+
if summary_data:
|
| 301 |
+
table_data[f"long_table_{table_index}_summary"] = summary_data
|
| 302 |
+
|
| 303 |
+
return table_data, table_paragraphs
|
| 304 |
+
|
| 305 |
+
# --- Non-Table Processing Functions ---
|
| 306 |
+
|
| 307 |
+
def extract_text_outside_tables(root, table_paragraphs):
|
| 308 |
+
"""Extracts text from paragraphs outside tables in the document."""
|
| 309 |
+
extracted_text = []
|
| 310 |
+
|
| 311 |
+
for paragraph in root.findall('.//w:p', NS):
|
| 312 |
+
if paragraph in table_paragraphs:
|
| 313 |
+
continue # Skip paragraphs inside tables
|
| 314 |
+
|
| 315 |
+
texts = [t.text.strip() for t in paragraph.findall('.//w:t', NS) if t.text]
|
| 316 |
+
line = clean_spaces(' '.join(texts).replace(':',':')) # Clean colons and spaces
|
| 317 |
+
|
| 318 |
+
if ':' in line:
|
| 319 |
+
extracted_text.append(line)
|
| 320 |
+
|
| 321 |
+
return extracted_text
|
| 322 |
+
|
| 323 |
+
# --- Main Extraction Functions ---
|
| 324 |
+
|
| 325 |
+
def extract_docx_as_xml(file_bytes, save_xml=False, xml_filename="document.xml"):
|
| 326 |
+
|
| 327 |
+
# Ensure file_bytes is at the start position
|
| 328 |
+
file_bytes.seek(0)
|
| 329 |
+
|
| 330 |
+
with zipfile.ZipFile(file_bytes, 'r') as docx:
|
| 331 |
+
with docx.open('word/document.xml') as xml_file:
|
| 332 |
+
xml_content = xml_file.read().decode('utf-8')
|
| 333 |
+
if save_xml:
|
| 334 |
+
with open(xml_filename, "w", encoding="utf-8") as f:
|
| 335 |
+
f.write(xml_content)
|
| 336 |
+
return xml_content
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def xml_to_json(xml_content, save_json=False, json_filename="extracted_data.json"):
|
| 340 |
+
|
| 341 |
+
tree = ET.ElementTree(ET.fromstring(xml_content))
|
| 342 |
+
root = tree.getroot()
|
| 343 |
+
|
| 344 |
+
table_data, table_paragraphs = extract_tables(root)
|
| 345 |
+
extracted_data = table_data
|
| 346 |
+
extracted_data["non_table_data"] = extract_text_outside_tables(root, table_paragraphs)
|
| 347 |
+
|
| 348 |
+
if save_json:
|
| 349 |
+
with open(json_filename, "w", encoding="utf-8") as f:
|
| 350 |
+
json.dump(extracted_data, f, ensure_ascii=False, indent=4)
|
| 351 |
+
|
| 352 |
+
return json.dumps(extracted_data, ensure_ascii=False, indent=4)
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def deepseek_extract_contract_summary(json_data, save_json=False, json_filename="contract_summary.json"):
|
| 356 |
+
"""Sends extracted JSON data to OpenAI and returns formatted structured JSON."""
|
| 357 |
+
|
| 358 |
+
# Step 1: Convert JSON string to Python dictionary
|
| 359 |
+
contract_data = json.loads(json_data)
|
| 360 |
+
|
| 361 |
+
# Step 2: Remove keys that contain "long_table"
|
| 362 |
+
filtered_contract_data = {key: value for key, value in contract_data.items() if "long_table" not in key}
|
| 363 |
+
|
| 364 |
+
# Step 3: Convert back to JSON string (if needed)
|
| 365 |
+
json_output = json.dumps(contract_data, ensure_ascii=False, indent=4)
|
| 366 |
+
|
| 367 |
+
prompt = """You are given a contract in JSON format. Extract the following information:
|
| 368 |
+
|
| 369 |
+
# Response Format
|
| 370 |
+
Return the extracted information as a structured JSON in the exact format shown below (Note: Do not repeat any keys, if unsure leave the value empty):
|
| 371 |
+
|
| 372 |
+
{
|
| 373 |
+
"合同编号":
|
| 374 |
+
"接收人": (注意:不是买家必须是接收人,不是一个公司而是一个人)
|
| 375 |
+
"Recipient":
|
| 376 |
+
"接收地": (注意:不是交货地点是目的港,只写中文,英文写在 place of receipt)
|
| 377 |
+
"Place of receipt": (只写英文, 如果接收地/目的港/Port of destination 有英文可填在这里)
|
| 378 |
+
"供应商":
|
| 379 |
+
"币种": (主要用的货币,填英文缩写。GNF一般是为了方便而转换出来的, 除非只有GNF,GNF一般不是主要币种。)
|
| 380 |
+
"供货日期": (如果合同里有写才填,不要自己推理出日期,必须是一个日期,而不是天数)
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
Contract data in JSON format:""" + f"""
|
| 384 |
+
{json_output}"""
|
| 385 |
+
|
| 386 |
+
messages = [
|
| 387 |
+
{
|
| 388 |
+
"role": "user",
|
| 389 |
+
"content": prompt
|
| 390 |
+
}
|
| 391 |
+
]
|
| 392 |
+
|
| 393 |
+
# Deepseek R1 Distilled Qwen 2.5 14B --------------------------------
|
| 394 |
+
client = OpenAI(
|
| 395 |
+
base_url="https://router.huggingface.co/novita",
|
| 396 |
+
api_key=HF_API_KEY,
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
completion = client.chat.completions.create(
|
| 400 |
+
model="deepseek/deepseek-r1-distill-qwen-14b",
|
| 401 |
+
messages=messages,
|
| 402 |
+
temperature=0.5,
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
think_text = re.findall(r"<think>(.*?)</think>", completion.choices[0].message.content, flags=re.DOTALL)
|
| 406 |
+
if think_text:
|
| 407 |
+
print(f"Thought Process: {think_text}")
|
| 408 |
+
logging.info(f"Think text: {think_text}")
|
| 409 |
+
|
| 410 |
+
contract_summary = re.sub(r"<think>.*?</think>\s*", "", completion.choices[0].message.content, flags=re.DOTALL) # Remove think
|
| 411 |
+
|
| 412 |
+
contract_summary = re.sub(r"^```json\n|```$", "", contract_summary, flags=re.DOTALL) # Remove ```
|
| 413 |
+
|
| 414 |
+
if save_json:
|
| 415 |
+
with open(json_filename, "w", encoding="utf-8") as f:
|
| 416 |
+
f.write(contract_summary)
|
| 417 |
+
|
| 418 |
+
return json.dumps(contract_summary, ensure_ascii=False, indent=4)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def deepseek_extract_price_list(json_data):
|
| 422 |
+
"""Sends extracted JSON data to OpenAI and returns formatted structured JSON."""
|
| 423 |
+
|
| 424 |
+
# Step 1: Convert JSON string to Python dictionary
|
| 425 |
+
contract_data = json.loads(json_data)
|
| 426 |
+
|
| 427 |
+
# Step 2: Remove keys that contain "long_table"
|
| 428 |
+
filtered_contract_data = {key: value for key, value in contract_data.items() if "long_table" in key}
|
| 429 |
+
|
| 430 |
+
# Step 3: Convert back to JSON string (if needed)
|
| 431 |
+
json_output = json.dumps(filtered_contract_data, ensure_ascii=False, indent=4)
|
| 432 |
+
|
| 433 |
+
prompt = """You are given a price list in JSON format. Extract the following information in CSV format:
|
| 434 |
+
|
| 435 |
+
# Response Format
|
| 436 |
+
Return the extracted information as a CSV in the exact format shown below:
|
| 437 |
+
|
| 438 |
+
物料名称, 物料名称(英文), 物料规格, 采购数量, 单位, 单价, 计划号
|
| 439 |
+
|
| 440 |
+
JSON data:""" + f"""
|
| 441 |
+
{json_output}"""
|
| 442 |
+
|
| 443 |
+
messages = [
|
| 444 |
+
{
|
| 445 |
+
"role": "user",
|
| 446 |
+
"content": prompt
|
| 447 |
+
}
|
| 448 |
+
]
|
| 449 |
+
|
| 450 |
+
client = OpenAI(
|
| 451 |
+
base_url="https://router.huggingface.co/novita",
|
| 452 |
+
api_key=HF_API_KEY,
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
completion = client.chat.completions.create(
|
| 456 |
+
model="deepseek/deepseek-r1-distill-qwen-14b",
|
| 457 |
+
messages=messages,
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
price_list = re.sub(r"<think>.*?</think>\s*", "", completion.choices[0].message.content, flags=re.DOTALL)
|
| 461 |
+
|
| 462 |
+
price_list = re.sub(r"^```json\n|```$", "", price_list, flags=re.DOTALL)
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def json_to_excel(contract_summary, json_data, excel_path):
|
| 466 |
+
"""Converts extracted JSON tables to an Excel file."""
|
| 467 |
+
|
| 468 |
+
# Correctly parse the JSON string
|
| 469 |
+
contract_summary_json = json.loads(json.loads(contract_summary))
|
| 470 |
+
|
| 471 |
+
contract_summary_df = pd.DataFrame([contract_summary_json])
|
| 472 |
+
|
| 473 |
+
# Ensure json_data is a dictionary
|
| 474 |
+
if isinstance(json_data, str):
|
| 475 |
+
json_data = json.loads(json_data)
|
| 476 |
+
|
| 477 |
+
long_tables = [pd.DataFrame(table) for key, table in json_data.items() if "long_table" in key and "summary" not in key]
|
| 478 |
+
long_table = long_tables[-1] if long_tables else pd.DataFrame()
|
| 479 |
+
|
| 480 |
+
with pd.ExcelWriter(excel_path) as writer:
|
| 481 |
+
contract_summary_df.to_excel(writer, sheet_name="Contract Summary", index=False)
|
| 482 |
+
long_table.to_excel(writer, sheet_name="Price List", index=False)
|
| 483 |
+
|
| 484 |
+
#--- Extract PO ------------------------------
|
| 485 |
+
|
| 486 |
+
def extract_po(docx_path):
|
| 487 |
+
"""Processes a single .docx file, extracts tables, formats with OpenAI, and returns combined JSON data."""
|
| 488 |
+
if not os.path.exists(docx_path) or not docx_path.endswith(".docx"):
|
| 489 |
+
raise ValueError(f"Invalid file: {docx_path}")
|
| 490 |
+
|
| 491 |
+
# Read the .docx file as bytes
|
| 492 |
+
with open(docx_path, "rb") as f:
|
| 493 |
+
docx_bytes = BytesIO(f.read())
|
| 494 |
+
|
| 495 |
+
# Step 1: Extract XML content from DOCX
|
| 496 |
+
print("Extracting Docs data to XML...")
|
| 497 |
+
xml_filename = os.path.splitext(os.path.basename(docx_path))[0] + "_document.xml"
|
| 498 |
+
xml_file = extract_docx_as_xml(docx_bytes, save_xml=True, xml_filename=xml_filename)
|
| 499 |
+
|
| 500 |
+
get_namespace(ET.fromstring(xml_file))
|
| 501 |
+
|
| 502 |
+
# Step 2: Extract tables from DOCX and save JSON
|
| 503 |
+
print("Extracting XML data to JSON...")
|
| 504 |
+
json_filename = os.path.splitext(os.path.basename(docx_path))[0] + "_extracted_data.json"
|
| 505 |
+
extracted_data = xml_to_json(xml_file, save_json=True, json_filename=json_filename)
|
| 506 |
+
|
| 507 |
+
# Step 3: Process JSON with OpenAI to get structured output
|
| 508 |
+
print("Processing JSON data with AI...")
|
| 509 |
+
contract_summary_filename = os.path.splitext(os.path.basename(docx_path))[0] + "_contract_summary.json"
|
| 510 |
+
contract_summary = deepseek_extract_contract_summary(extracted_data, save_json=True, json_filename=contract_summary_filename)
|
| 511 |
+
|
| 512 |
+
# Step 4: Combine contract summary and long table data into a single JSON object
|
| 513 |
+
print("Combining AI Generated JSON with Extracted Data...")
|
| 514 |
+
combined_data = {
|
| 515 |
+
"contract_summary": json.loads(json.loads(contract_summary)),
|
| 516 |
+
"price_list": [
|
| 517 |
+
table for key, table in json.loads(extracted_data).items()
|
| 518 |
+
if "long_table" in key and "summary" not in key
|
| 519 |
+
]
|
| 520 |
+
}
|
| 521 |
+
|
| 522 |
+
# Logging
|
| 523 |
+
log = f"""Results:
|
| 524 |
+
|
| 525 |
+
Contract Summary: {contract_summary},
|
| 526 |
+
|
| 527 |
+
RAW Extracted Data: {extracted_data},
|
| 528 |
+
|
| 529 |
+
Combined JSON: {json.dumps(combined_data, ensure_ascii=False, indent=4)}"""
|
| 530 |
+
|
| 531 |
+
print(log)
|
| 532 |
+
logging.info(f"""{log}""")
|
| 533 |
+
|
| 534 |
+
return combined_data
|
| 535 |
+
|
| 536 |
+
# Example Usage
|
| 537 |
+
|
| 538 |
+
# extract_po("test-contract-converted.docx")
|
| 539 |
+
# extract_po("test-contract.docx")
|
| 540 |
+
|
| 541 |
+
# Gradio Interface ------------------------------
|
| 542 |
+
|
| 543 |
+
import gradio as gr
|
| 544 |
+
from gradio.themes.base import Base
|
| 545 |
+
|
| 546 |
+
interface = gr.Interface(
|
| 547 |
+
fn=extract_po,
|
| 548 |
+
title="PO Extractor 买卖合同数据提取",
|
| 549 |
+
inputs=gr.File(label="买卖合同 (.docx)"),
|
| 550 |
+
outputs=gr.Json(label="提取结果"),
|
| 551 |
+
flagging_mode="never",
|
| 552 |
+
theme=Base()
|
| 553 |
+
)
|
| 554 |
+
|
| 555 |
+
interface.launch()
|