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