Spaces:
Build error
Build error
Update main.py
Browse files5 unmodified lines678910111214 unmodified lines27282930313233343536376 unmodified lines4445464748495051525354555657585960616263645 unmodified lines70717273747576778 unmodified lines86878889909192939495969798991001011021031041051061071081091101111121131141151161171185 unmodified linesfrom typing import List, Dict, Optionalfrom dataclasses import dataclass, asdictfrom mineru import Mineru, Layout, Tablefrom sentence_transformers import SentenceTransformerfrom llama_cpp import Llamafrom fastapi.encoders import jsonable_encoder14 unmodified linesclass PDFProcessor:def __init__(self):self.mineru = Mineru()self.emb_model = SentenceTransformer('all-MiniLM-L6-v2')# Initialize LLM with automatic downloadself.llm = self._initialize_llm()def _initialize_llm(self):"""Initialize LLM with automatic download if needed"""6 unmodified linesverbose=False)def extract_layout(self, pdf_path: str) -> List[Layout]:"""Extract structured layout using MinerU"""return self.mineru.process_pdf(pdf_path)def process_tables(self, tables: List[Table]) -> List[Dict]:"""Convert MinerU tables to structured format"""return [{"page": table.page_number,"cells": table.cells,"header": table.headers,"content": table.content} for table in tables]def generate_query_prompt(self, text: str) -> str:"""Create optimized extraction prompt"""return f"""Extract product specifications from this text:{text}5 unmodified lines"attributes": {{ "key": "value" }}}}"""def parse_response(self, response: str) -> Optional[ProductSpec]:"""Robust JSON parsing with fallbacks"""try:json_start = response.find('{')json_end = response.rfind('}') + 18 unmodified lineslogger.warning(f"Parse error: {e}")return Nonedef process_pdf(self, pdf_path: str) -> Dict:"""Main processing pipeline"""start_time = time.time()# Extract structured contentlayout = self.extract_layout(pdf_path)tables = self.process_tables(layout.tables)# Process text blocksproducts = []for block in layout.text_blocks:prompt = self.generate_query_prompt(block.text)# Generate response with hardware optimizationresponse = self.llm.create_chat_completion(messages=[{"role": "user", "content": prompt}],temperature=0.1,max_tokens=512)if product := self.parse_response(response['choices'][0]['message']['content']):product.tables = tablesproducts.append(product.to_dict())logger.info(f"Processed {len(products)} products in {time.time()-start_time:.2f}s")return {"products": products, "tables": tables}def process_pdf_catalog(pdf_path: str):processor = PDFProcessor()try:5 unmodified lines678910111213141514 unmodified lines303132333435363738396 unmodified lines4647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331345 unmodified lines1401411421431441451461478 unmodified lines1561571581591601615 unmodified linesfrom typing import List, Dict, Optionalfrom dataclasses import dataclass, asdictfrom magic_pdf.data.data_reader_writer import FileBasedDataWriter, FileBasedDataReaderfrom magic_pdf.data.dataset import PymuDocDatasetfrom magic_pdf.model.doc_analyze_by_custom_model import doc_analyzefrom magic_pdf.config.enums import SupportedPdfParseMethodfrom sentence_transformers import SentenceTransformerfrom llama_cpp import Llamafrom fastapi.encoders import jsonable_encoder14 unmodified linesclass PDFProcessor:def __init__(self):self.emb_model = SentenceTransformer('all-MiniLM-L6-v2')self.llm = self._initialize_llm()self.output_dir = Path("./output")self.output_dir.mkdir(exist_ok=True)def _initialize_llm(self):"""Initialize LLM with automatic download if needed"""6 unmodified linesverbose=False)def process_pdf(self, pdf_path: str) -> Dict:"""Process PDF using MinerU pipeline"""start_time = time.time()# Initialize MinerU componentslocal_image_dir = self.output_dir / "images"local_md_dir = self.output_dirimage_dir = str(local_image_dir.name)os.makedirs(local_image_dir, exist_ok=True)image_writer = FileBasedDataWriter(str(local_image_dir))md_writer = FileBasedDataWriter(str(local_md_dir))# Read PDFreader = FileBasedDataReader("")pdf_bytes = reader.read(pdf_path)# Create dataset and processds = PymuDocDataset(pdf_bytes)if ds.classify() == SupportedPdfParseMethod.OCR:infer_result = ds.apply(doc_analyze, ocr=True)pipe_result = infer_result.pipe_ocr_mode(image_writer)else:infer_result = ds.apply(doc_analyze, ocr=False)pipe_result = infer_result.pipe_txt_mode(image_writer)# Get structured contentmiddle_json = pipe_result.get_middle_json()tables = self._extract_tables(middle_json)text_blocks = self._extract_text_blocks(middle_json)# Process text blocks with LLMproducts = []for block in text_blocks:product = self._process_text_block(block)if product:product.tables = tablesproducts.append(product.to_dict())logger.info(f"Processed {len(products)} products in {time.time()-start_time:.2f}s")return {"products": products, "tables": tables}def _extract_tables(self, middle_json: Dict) -> List[Dict]:"""Extract tables from MinerU's middle JSON"""tables = []for page in middle_json.get('pages', []):for table in page.get('tables', []):tables.append({"page": page.get('page_number'),"cells": table.get('cells', []),"header": table.get('header', []),"content": table.get('content', [])})return tablesdef _extract_text_blocks(self, middle_json: Dict) -> List[str]:"""Extract text blocks from MinerU's middle JSON"""text_blocks = []for page in middle_json.get('pages', []):for block in page.get('blocks', []):if block.get('type') == 'text':text_blocks.append(block.get('text', ''))return text_blocksdef _process_text_block(self, text: str) -> Optional[ProductSpec]:"""Process text block with LLM"""prompt = self._generate_query_prompt(text)try:response = self.llm.create_chat_completion(messages=[{"role": "user", "content": prompt}],temperature=0.1,max_tokens=512)return self._parse_response(response['choices'][0]['message']['content'])except Exception as e:logger.warning(f"Error processing text block: {e}")return Nonedef _generate_query_prompt(self, text: str) -> str:"""Generate extraction prompt"""return f"""Extract product specifications from this text:{text}5 unmodified lines"attributes": {{ "key": "value" }}}}"""def _parse_response(self, response: str) -> Optional[ProductSpec]:"""Parse LLM response"""try:json_start = response.find('{')json_end = response.rfind('}') + 18 unmodified lineslogger.warning(f"Parse error: {e}")return Nonedef process_pdf_catalog(pdf_path: str):processor = PDFProcessor()try:
main.py+89-46