File size: 27,888 Bytes
a519263 c7743de a519263 d916930 a519263 d916930 a519263 d916930 a519263 d916930 a519263 d916930 a519263 |
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 |
import sys
import os
from pathlib import Path
import requests
import re
import tempfile
import json
import math
import time
import warnings
from typing import Dict, List
from urllib3.exceptions import IncompleteRead
from datetime import datetime
import docling
from docling.document_converter import DocumentConverter, PdfFormatOption
from docling.datamodel.base_models import InputFormat
from docling.datamodel.pipeline_options import PdfPipelineOptions
from docling.backend.pypdfium2_backend import PyPdfiumDocumentBackend
import pandas as pd
import gradio as gr
from pymongo import MongoClient, UpdateOne
from pymongo.errors import ConnectionFailure, OperationFailure
from data_helper import *
from config import MONGODB_URI, MONGODB_DATABASE
# Suppress PyTorch DataLoader pin_memory warning on MPS
warnings.filterwarnings("ignore", message=".*pin_memory.*not supported on MPS.*")
class MongoDBHandler:
"""Handler for MongoDB operations"""
def __init__(self, connection_string: str = None, database_name: str = MONGODB_DATABASE):
"""
Initialize MongoDB connection
Args:
connection_string: MongoDB connection string (default: localhost)
database_name: Name of the database to use
"""
if connection_string is None:
connection_string = "mongodb://localhost:27017/"
self.connection_string = connection_string
self.database_name = database_name
self.client = None
self.db = None
def connect(self):
"""Establish connection to MongoDB"""
try:
self.client = MongoClient(self.connection_string, serverSelectionTimeoutMS=5000)
# Test connection
self.client.admin.command('ping')
self.db = self.client[self.database_name]
print(f"✅ Connected to MongoDB database: {self.database_name}")
return True
except ConnectionFailure as e:
print(f"❌ Failed to connect to MongoDB: {e}")
return False
except Exception as e:
print(f"❌ Unexpected error connecting to MongoDB: {e}")
return False
def disconnect(self):
"""Close MongoDB connection"""
if self.client is not None:
self.client.close()
print("🔌 Disconnected from MongoDB")
def get_collection_name(self, category: str) -> str:
"""Map category name to collection name"""
collection_mapping = {
"Sản phẩm nhà thông minh": "sp_nha_thong_minh",
"Đèn LED": "sp_chieu_sang",
"Chiếu sáng chuyên dụng": "sp_chuyen_dung",
"Thiết bị điện": "sp_thiet_bi_dien",
"Phích nước": "sp_phich_nuoc",
}
return collection_mapping.get(category, "unknown_products")
def upload_data(self, data: List[Dict], collection_name: str, upsert: bool = True) -> Dict:
"""
Upload data to MongoDB collection
Args:
data: List of product dictionaries
collection_name: Name of the collection
upsert: If True, update existing documents or insert new ones
Returns:
Dictionary with upload statistics
"""
if self.db is None:
return {"success": False, "error": "Not connected to database"}
if not data:
return {"success": False, "error": "No data to upload"}
try:
collection = self.db[collection_name]
# Add metadata
timestamp = datetime.utcnow()
for item in data:
item['_updated_at'] = timestamp
if '_created_at' not in item:
item['_created_at'] = timestamp
if upsert:
# Use bulk write with upsert for better performance
operations = []
for item in data:
product_id = item.get('Product_ID')
if product_id:
operations.append(
UpdateOne(
{'Product_ID': product_id},
{'$set': item},
upsert=True
)
)
if operations:
result = collection.bulk_write(operations)
return {
"success": True,
"collection": collection_name,
"inserted": result.upserted_count,
"modified": result.modified_count,
"matched": result.matched_count,
"total": len(data)
}
else:
return {"success": False, "error": "No valid product IDs found"}
else:
# Simple insert (may cause duplicates)
result = collection.insert_many(data)
return {
"success": True,
"collection": collection_name,
"inserted": len(result.inserted_ids),
"total": len(data)
}
except OperationFailure as e:
return {"success": False, "error": f"MongoDB operation failed: {e}"}
except Exception as e:
return {"success": False, "error": f"Unexpected error: {e}"}
def test_connection(self) -> str:
"""Test MongoDB connection and return status"""
try:
if self.connect():
# Get database stats
stats = self.db.command("dbstats")
collections = self.db.list_collection_names()
self.disconnect()
return f"✅ Connected successfully!\n📊 Database: {self.database_name}\n📁 Collections: {len(collections)}\n💾 Size: {stats.get('dataSize', 0) / 1024 / 1024:.2f} MB"
else:
return "❌ Connection failed"
except Exception as e:
return f"❌ Error: {str(e)}"
class DataProcessing:
def __init__(self):
pass
def get_data_from_excel_file(self, excel_path, key_match, collection_name,
processor_type="docling", mongo_handler=None):
"""
Process Excel file and upload to MongoDB
Args:
excel_path: Path to Excel file
key_match: Category to match
collection_name: MongoDB collection name
processor_type: Type of PDF processor
mongo_handler: MongoDBHandler instance (required)
"""
if not mongo_handler:
return "❌ MongoDB handler not provided"
all_sheets = pd.read_excel(excel_path, sheet_name=None, header=1)
sheet_names = list(all_sheets.keys())
sheets = {k: all_sheets[k] for k in sheet_names[2:]}
data = []
for sheet_name, df in sheets.items():
df.columns = df.columns.str.strip()
if "category 1" not in df.columns:
df = pd.read_excel(excel_path, sheet_name=sheet_name, header=0)
df.columns = df.columns.str.strip()
if "category 1" in df.columns:
filtered = df[df["category 1"].astype(str).str.replace("\n", " ").str.strip() == key_match]
data.append(filtered)
if data:
result_df = pd.concat(data, ignore_index=True)
result_df = result_df.where(pd.notnull(result_df), None)
result_df["HDSD"] = None
cols_to_drop = [col for col in result_df.columns if col.strip().lower().startswith("unnamed") or col.strip() == "a" or col == "STT"]
result_df = result_df.drop(columns=cols_to_drop, errors='ignore')
cols_to_replace = [col for col in result_df.columns if col not in ["Tóm tắt ưu điểm, tính năng", "Thông số kỹ thuật", "Nội dung Ưu điểm SP", "Ưu điểm"]]
result_df[cols_to_replace] = result_df[cols_to_replace].replace('\n', ' ', regex=True)
# Replace "none" values with None
result_df.loc[result_df["Thông số kỹ thuật"] == "none", "Thông số kỹ thuật"] = None
result_df.loc[result_df["Tóm tắt ưu điểm, tính năng"] == "none", "Tóm tắt ưu điểm, tính năng"] = None
result_df.loc[result_df["Tóm tắt TSKT"] == "none", "Tóm tắt TSKT"] = None
result_df.loc[result_df["Nội dung Ưu điểm SP"] == "none", "Nội dung Ưu điểm SP"] = None
result_df = result_df.map(lambda x: x.strip() if isinstance(x, str) else x)
result_df.drop_duplicates(subset=["Product_ID"], inplace=True)
result_df = self.data_normalization(result_df=result_df)
data = result_df.to_dict(orient="records")
data = self.convert_floats(data)
data = self.replace_nan_with_none(data)
# Process instructions based on processor type
if processor_type == "docling_with_ocr":
data = self.process_instruction_with_tesseract(data)
else:
data = self.process_instruction(data)
# Upload to MongoDB
if not mongo_handler.connect():
return "❌ Failed to connect to MongoDB"
result = mongo_handler.upload_data(data, collection_name, upsert=True)
mongo_handler.disconnect()
if result.get("success"):
return f"✅ Uploaded to MongoDB collection '{result['collection']}':\n" \
f" • Total records: {result['total']}\n" \
f" • Inserted: {result.get('inserted', 0)}\n" \
f" • Updated: {result.get('modified', 0)}"
else:
return f"❌ MongoDB upload failed: {result.get('error', 'Unknown error')}"
else:
return f"❌ Data not found for key: {key_match}"
def convert_floats(self, obj):
if isinstance(obj, float) and obj.is_integer():
return int(obj)
elif isinstance(obj, list):
return [self.convert_floats(i) for i in obj]
elif isinstance(obj, dict):
return {k: self.convert_floats(v) for k, v in obj.items()}
else:
return obj
def strip_redundant_space(self, text):
cleaned_text = " ".join(text.strip().split())
return cleaned_text
def convert_tag_to_dict(self, tag_str: str) -> dict:
if not isinstance(tag_str, str) or not tag_str.strip().startswith("{"):
return {}
try:
fixed = re.sub(r'([{,]\s*)(\w+)\s*:', r'\1"\2":', tag_str)
raw_pairs = fixed.strip('{} ').split(',')
raw_pairs = [pair.strip() for pair in raw_pairs if pair.strip()]
result = {}
current_key = None
for pair in raw_pairs:
if ':' in pair:
key, value = pair.split(':', 1)
key = key.strip().strip('"')
value = value.strip()
pattern = r',\s[A-Z]'
match = re.search(pattern, value)
if match:
values = [v.strip() for v in value.split(',')]
else:
values = value
result[key] = values
current_key = key
elif current_key:
previous_value = result[current_key]
if isinstance(previous_value, list):
result[current_key].append(pair.strip())
else:
result[current_key] = [previous_value, pair.strip()]
return result
except Exception as e:
print(f"Error parse tag: {tag_str} -> {e}")
return {}
def convert_tags_to_numeric(self, tags_dict):
keys_to_convert = ["dung_tich", "cong_suat", "lo_khoet_tran", "so_cuc", "so_hat", "modules", "cuon_day", "kich_thuoc"]
new_tags = {}
for key, value in tags_dict.items():
if key in keys_to_convert:
match = re.search(r'([\d.]+)', str(value))
if match:
num = float(match.group(1))
new_tags[key] = int(num) if num.is_integer() else num
else:
new_tags[key] = value
else:
new_tags[key] = value
return new_tags
def data_normalization(self, result_df):
if "Tags" in result_df.columns:
result_df["Tags"] = result_df["Tags"].astype(str).str.lower().apply(self.convert_tag_to_dict)
result_df["Tags"] = result_df["Tags"].apply(self.convert_tags_to_numeric)
if "Giá" in result_df.columns:
result_df["Giá"] = result_df["Giá"].apply(lambda x: "Liên hệ" if x == 0 else x)
if "Tên sản phẩm" in result_df.columns:
result_df["Tên sản phẩm"] = result_df["Tên sản phẩm"].apply(self.strip_redundant_space)
for col_name in result_df.columns:
if col_name in ["Tóm tắt TSKT", "Thông số kỹ thuật"]:
result_df[col_name] = result_df[col_name].astype(str).str.lower().str.strip()
return result_df
def replace_nan_with_none(self, obj):
if isinstance(obj, float) and math.isnan(obj):
return None
elif isinstance(obj, dict):
return {k: self.replace_nan_with_none(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [self.replace_nan_with_none(i) for i in obj]
else:
return obj
@staticmethod
def download_pdf_with_retry(url, max_retries=3, timeout=30):
"""Download PDF with retry logic and better error handling"""
for attempt in range(max_retries):
try:
print(f"Downloading PDF (attempt {attempt + 1}/{max_retries})...")
session = requests.Session()
session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
})
response = session.get(url, stream=True, timeout=timeout)
response.raise_for_status()
content_length = response.headers.get('content-length')
if content_length:
print(f"Expected file size: {int(content_length):,} bytes")
content = b''
chunk_size = 8192
downloaded = 0
for chunk in response.iter_content(chunk_size=chunk_size):
if chunk:
content += chunk
downloaded += len(chunk)
print(f"\nDownload completed: {len(content):,} bytes")
return content
except (requests.exceptions.RequestException, IncompleteRead, ConnectionError) as e:
print(f"Download attempt {attempt + 1} failed: {e}")
if attempt < max_retries - 1:
wait_time = 2 ** attempt
print(f"Waiting {wait_time} seconds before retry...")
time.sleep(wait_time)
else:
print("All download attempts failed")
raise e
@staticmethod
def process_pdf_with_docling(url):
"""Process PDF from URL using Docling for better structure extraction"""
try:
pdf_content = DataProcessing.download_pdf_with_retry(url)
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
tmp_file.write(pdf_content)
tmp_path = tmp_file.name
print(f"PDF saved to temporary file: {tmp_path}")
pipeline_options = PdfPipelineOptions()
pipeline_options.do_ocr = False
pipeline_options.do_table_structure = False
converter = DocumentConverter(
format_options={
InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options)
}
)
print("Converting document with Docling...")
result = converter.convert(tmp_path)
os.unlink(tmp_path)
print("Temporary file cleaned up")
return result
except Exception as e:
print(f"Error processing PDF with Docling from URL {url}: {e}")
return None
@staticmethod
def extract_content_from_docling_result(docling_result):
"""Extract content from Docling result in a more robust way"""
if not docling_result:
return None
try:
doc = docling_result.document
try:
markdown_content = doc.export_to_markdown()
return {'markdown': markdown_content}
except Exception as e:
print(f"Markdown export failed: {e}")
if hasattr(doc, 'main_text'):
return {'text': doc.main_text}
if hasattr(doc, 'body') and doc.body:
content = []
for element in doc.body:
content.append(str(element))
return {'text': '\n'.join(content)}
if hasattr(doc, 'elements') and doc.elements:
content = []
for element in doc.elements:
content.append(str(element))
return {'text': '\n'.join(content)}
return {'error': 'No accessible content found'}
except Exception as e:
return {'error': f"Error extracting content: {e}"}
def process_instruction(self, data):
"""Lấy thông tin hướng dẫn sử dụng"""
tmp_data = data[:]
for item in tmp_data:
instruction_url = item.get("Link file HDSD", None)
if not instruction_url:
print("No instruction URL found, skipping...")
item["HDSD"] = ""
continue
if "https://" not in instruction_url and "http://" not in instruction_url:
print("Wrong URL, but has instruction info")
item["HDSD"] = instruction_url
continue
if "hdsd" not in instruction_url or "Khong" in instruction_url:
print("invalid instruction url/content")
item["HDSD"] = ""
continue
raw_result = DataProcessing.process_pdf_with_docling(instruction_url)
if raw_result:
extract_result = DataProcessing.extract_content_from_docling_result(raw_result)
if 'markdown' in extract_result.keys():
item["HDSD"] = re.sub(r"<!--\s*image\s*-->", '', extract_result['markdown'], flags=re.IGNORECASE).strip()
elif 'text' in extract_result.keys():
item["HDSD"] = re.sub(r"<!--\s*image\s*-->", '', extract_result['text'], flags=re.IGNORECASE).strip()
return tmp_data
def process_single_category(excel_path, category_name, processor_type,
mongo_connection, mongo_database,
progress=gr.Progress()):
"""Process a single product category and upload to MongoDB"""
if excel_path is None:
return "❌ Please upload an Excel file first"
# Category mapping
category_mapping = {
"Sản phẩm nhà thông minh": ("Sản phẩm nhà thông minh", "sp_nha_thong_minh"),
"Đèn LED": ("Đèn LED", "sp_chieu_sang"),
"Chiếu sáng chuyên dụng": ("Chiếu sáng chuyên dụng", "sp_chuyen_dung"),
"Thiết bị điện": ("Thiết bị điện", "sp_thiet_bi_dien"),
"Phích nước": ("Phích nước", "sp_phich_nuoc"),
}
if category_name not in category_mapping:
return f"❌ Unknown category: {category_name}"
key_match, collection_name = category_mapping[category_name]
try:
progress(0.1, desc="Initializing data processor...")
dp = DataProcessing()
# Initialize MongoDB handler
mongo_handler = MongoDBHandler(
connection_string=mongo_connection if mongo_connection else None,
database_name=mongo_database if mongo_database else MONGODB_DATABASE
)
progress(0.3, desc=f"Processing {category_name} with {processor_type}...")
result = dp.get_data_from_excel_file(
excel_path=excel_path,
key_match=key_match,
collection_name=collection_name,
processor_type=processor_type,
mongo_handler=mongo_handler
)
progress(1.0, desc="Processing completed!")
return result
except Exception as e:
return f"❌ Error processing {category_name}: {str(e)}"
def process_all_categories(excel_path, processor_type,
mongo_connection, mongo_database, progress=gr.Progress()):
"""Process all product categories and upload to MongoDB"""
if excel_path is None:
return "❌ Please upload an Excel file first"
categories = [
"Sản phẩm nhà thông minh",
"Đèn LED",
"Chiếu sáng chuyên dụng",
"Thiết bị điện",
"Phích nước"
]
results = []
total_categories = len(categories)
for i, category in enumerate(categories):
progress((i + 1) / total_categories, desc=f"Processing {category}...")
result = process_single_category(
excel_path, category, processor_type,
mongo_connection, mongo_database
)
results.append(f"{category}: {result}")
return "\n".join(results)
def test_mongo_connection(connection_string, database_name):
"""Test MongoDB connection"""
if not connection_string:
connection_string = "mongodb://localhost:27017/"
if not database_name:
database_name = MONGODB_DATABASE
handler = MongoDBHandler(connection_string, database_name)
return handler.test_connection()
def create_processing_interface():
"""Create Gradio interface with MongoDB-only storage"""
with gr.Blocks(title="Data Processing - Product Metadata Extractor") as demo:
gr.Markdown("# 📊 Product Data Processing")
gr.Markdown("Extract and process product metadata from Excel files and upload to MongoDB")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### 📤 Upload Excel File")
excel_upload = gr.File(
label="Upload Excel File",
file_types=[".xlsx", ".xls"],
type="filepath"
)
gr.Markdown("### ⚙️ Processing Settings")
processor_dropdown = gr.Dropdown(
choices=["docling"],
value="docling",
label="PDF Processor Type",
info="Using basic docling for fast processing"
)
category_dropdown = gr.Dropdown(
choices=[
"Sản phẩm nhà thông minh",
"Đèn LED",
"Chiếu sáng chuyên dụng",
"Thiết bị điện",
"Phích nước"
],
value="Sản phẩm nhà thông minh",
label="Product Category",
info="Select which product category to process"
)
gr.Markdown("### 🗄️ MongoDB Configuration")
mongo_connection = gr.Textbox(
label="MongoDB Connection String",
placeholder="mongodb+srv://<username>:<password>@cluster.mongodb.net/?retryWrites=true&w=majority",
value=MONGODB_URI,
info="MongoDB connection string"
)
mongo_database = gr.Textbox(
label="Database Name",
placeholder="MONGODB_DATABASE",
value=MONGODB_DATABASE,
info="Name of the MongoDB database"
)
test_connection_btn = gr.Button("🔌 Test Connection", size="sm")
connection_status = gr.Textbox(
label="Connection Status",
interactive=False,
lines=3
)
with gr.Column(scale=2):
output_box = gr.Textbox(
lines=15,
label="📋 Processing Log",
placeholder="Processing results will appear here..."
)
gr.Markdown("### 🚀 Actions")
with gr.Row():
process_single_btn = gr.Button("🔄 Process Selected Category", variant="primary")
process_all_btn = gr.Button("🔄 Process All Categories", variant="secondary")
gr.Markdown("### 📖 Information")
with gr.Accordion("MongoDB Collections", open=False):
gr.Markdown("""
**📦 Collections**:
- `sp_nha_thong_minh` - Sản phẩm nhà thông minh
- `sp_chieu_sang` - Đèn LED
- `sp_chuyen_dung` - Chiếu sáng chuyên dụng
- `sp_thiet_bi_dien` - Thiết bị điện
- `sp_phich_nuoc` - Phích nước
**🔄 Upsert Logic**:
- Existing records are updated based on `Product_ID`
- New records are inserted automatically
- Timestamps `_created_at` and `_updated_at` are managed automatically
""")
with gr.Accordion("Processor Types", open=False):
gr.Markdown("""
**🔹 docling**: Basic PDF text extraction
- Fast processing
- Good for text-based PDFs
- No OCR capabilities
""")
# Event handlers
test_connection_btn.click(
fn=test_mongo_connection,
inputs=[mongo_connection, mongo_database],
outputs=[connection_status]
)
process_single_btn.click(
fn=process_single_category,
inputs=[
excel_upload, category_dropdown, processor_dropdown,
mongo_connection, mongo_database
],
outputs=output_box,
show_progress=True
)
process_all_btn.click(
fn=process_all_categories,
inputs=[
excel_upload, processor_dropdown,
mongo_connection, mongo_database
],
outputs=output_box,
show_progress=True
)
return demo
if __name__ == "__main__":
demo = create_processing_interface()
demo.launch(share=False, server_name="localhost", server_port=7860) |