[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6FK2GXVEEVTDWTDCJF7WX28":3,"skill-same:01M6FK2GXVEEVTDWTDCJF7WX28":67},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":34,"linkOnly":35,"markdownContent":36,"markdownBody":37,"frontMatter":38,"refName":40,"commitSha":41,"skillDirectory":42,"forksCount":43,"repositoryHtmlUrl":44,"repositoryHomepageUrl":6,"ownerHtmlUrl":45,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":46,"install":47,"resources":60},"01M6FK2GXVEEVTDWTDCJF7WX28","pdf-to-structured",null,"Extract structured data from construction PDFs. Convert specifications, BOMs, schedules, and reports from PDF to Excel\u002FCSV\u002FJSON. Use OCR for scanned documents and pdfplumber for native PDFs.","kbarbel640-del\u002Fskills","kbarbel640-del","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F255315490?v=4","01M6CJPPQGCCESXMG3K7BBGQ5J","01M6CJPPX2PB2BCZERFVM2C2B3",1,"MIT","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fdatadrivenconstruction\u002Fpdf-to-structured\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33],"PDF","structured","pdf to structured","xlsx","structured data","documents","csv","data","ocr","convert","json","extract","use","reports","native","specifications","2026-11-10 10:12:30",false,"---\r\nslug: \"pdf-to-structured\"\r\ndisplay_name: \"PDF To Structured\"\r\ndescription: \"Extract structured data from construction PDFs. Convert specifications, BOMs, schedules, and reports from PDF to Excel\u002FCSV\u002FJSON. Use OCR for scanned documents and pdfplumber for native PDFs.\"\r\n---\r\n\r\n# PDF to Structured Data Conversion\r\n\r\n## Overview\r\n\r\nBased on DDC methodology (Chapter 2.4), this skill transforms unstructured PDF documents into structured formats suitable for analysis and integration. Construction projects generate vast amounts of PDF documentation - specifications, BOMs, schedules, and reports - that need to be extracted and processed.\r\n\r\n**Book Reference:** \"Преобразование данных в структурированную форму\" \u002F \"Data Transformation to Structured Form\"\r\n\r\n> \"Преобразование данных из неструктурированной в структурированную форму — это и искусство, и наука. Этот процесс часто занимает значительную часть работы инженера по обработке данных.\"\r\n> — DDC Book, Chapter 2.4\r\n\r\n## ETL Process Overview\r\n\r\nThe conversion follows the ETL pattern:\r\n1. **Extract**: Load the PDF document\r\n2. **Transform**: Parse and structure the content\r\n3. **Load**: Save to CSV, Excel, or JSON\r\n\r\n## Quick Start\r\n\r\n```python\r\nimport pdfplumber\r\nimport pandas as pd\r\n\r\n# Extract table from PDF\r\nwith pdfplumber.open(\"construction_spec.pdf\") as pdf:\r\n    page = pdf.pages[0]\r\n    table = page.extract_table()\r\n    df = pd.DataFrame(table[1:], columns=table[0])\r\n    df.to_excel(\"extracted_data.xlsx\", index=False)\r\n```\r\n\r\n## Installation\r\n\r\n```bash\r\n# Core libraries\r\npip install pdfplumber pandas openpyxl\r\n\r\n# For scanned PDFs (OCR)\r\npip install pytesseract pdf2image\r\n# Also install Tesseract OCR: https:\u002F\u002Fgithub.com\u002Ftesseract-ocr\u002Ftesseract\r\n\r\n# For advanced PDF operations\r\npip install pypdf\r\n```\r\n\r\n## Native PDF Extraction (pdfplumber)\r\n\r\n### Extract All Tables from PDF\r\n\r\n```python\r\nimport pdfplumber\r\nimport pandas as pd\r\n\r\ndef extract_tables_from_pdf(pdf_path):\r\n    \"\"\"Extract all tables from a PDF file\"\"\"\r\n    all_tables = []\r\n\r\n    with pdfplumber.open(pdf_path) as pdf:\r\n        for page_num, page in enumerate(pdf.pages):\r\n            tables = page.extract_tables()\r\n            for table_num, table in enumerate(tables):\r\n                if table and len(table) > 1:\r\n                    # First row as header\r\n                    df = pd.DataFrame(table[1:], columns=table[0])\r\n                    df['_page'] = page_num + 1\r\n                    df['_table'] = table_num + 1\r\n                    all_tables.append(df)\r\n\r\n    if all_tables:\r\n        return pd.concat(all_tables, ignore_index=True)\r\n    return pd.DataFrame()\r\n\r\n# Usage\r\ndf = extract_tables_from_pdf(\"material_specification.pdf\")\r\ndf.to_excel(\"materials.xlsx\", index=False)\r\n```\r\n\r\n### Extract Text with Layout\r\n\r\n```python\r\nimport pdfplumber\r\n\r\ndef extract_text_with_layout(pdf_path):\r\n    \"\"\"Extract text preserving layout structure\"\"\"\r\n    full_text = []\r\n\r\n    with pdfplumber.open(pdf_path) as pdf:\r\n        for page in pdf.pages:\r\n            text = page.extract_text()\r\n            if text:\r\n                full_text.append(text)\r\n\r\n    return \"\\n\\n--- Page Break ---\\n\\n\".join(full_text)\r\n\r\n# Usage\r\ntext = extract_text_with_layout(\"project_report.pdf\")\r\nwith open(\"report_text.txt\", \"w\", encoding=\"utf-8\") as f:\r\n    f.write(text)\r\n```\r\n\r\n### Extract Specific Table by Position\r\n\r\n```python\r\nimport pdfplumber\r\nimport pandas as pd\r\n\r\ndef extract_table_from_area(pdf_path, page_num, bbox):\r\n    \"\"\"\r\n    Extract table from specific area on page\r\n\r\n    Args:\r\n        pdf_path: Path to PDF file\r\n        page_num: Page number (0-indexed)\r\n        bbox: Bounding box (x0, top, x1, bottom) in points\r\n    \"\"\"\r\n    with pdfplumber.open(pdf_path) as pdf:\r\n        page = pdf.pages[page_num]\r\n        cropped = page.within_bbox(bbox)\r\n        table = cropped.extract_table()\r\n\r\n        if table:\r\n            return pd.DataFrame(table[1:], columns=table[0])\r\n    return pd.DataFrame()\r\n\r\n# Usage - extract table from specific area\r\n# bbox format: (left, top, right, bottom) in points (1 inch = 72 points)\r\ndf = extract_table_from_area(\"drawing.pdf\", 0, (50, 100, 550, 400))\r\n```\r\n\r\n## Scanned PDF Processing (OCR)\r\n\r\n### Extract Text from Scanned PDF\r\n\r\n```python\r\nimport pytesseract\r\nfrom pdf2image import convert_from_path\r\nimport pandas as pd\r\n\r\ndef ocr_scanned_pdf(pdf_path, language='eng'):\r\n    \"\"\"\r\n    Extract text from scanned PDF using OCR\r\n\r\n    Args:\r\n        pdf_path: Path to scanned PDF\r\n        language: Tesseract language code (eng, deu, rus, etc.)\r\n    \"\"\"\r\n    # Convert PDF pages to images\r\n    images = convert_from_path(pdf_path, dpi=300)\r\n\r\n    extracted_text = []\r\n    for i, image in enumerate(images):\r\n        text = pytesseract.image_to_string(image, lang=language)\r\n        extracted_text.append({\r\n            'page': i + 1,\r\n            'text': text\r\n        })\r\n\r\n    return pd.DataFrame(extracted_text)\r\n\r\n# Usage\r\ndf = ocr_scanned_pdf(\"scanned_specification.pdf\", language='eng')\r\ndf.to_csv(\"ocr_results.csv\", index=False)\r\n```\r\n\r\n### OCR Table Extraction\r\n\r\n```python\r\nimport pytesseract\r\nfrom pdf2image import convert_from_path\r\nimport pandas as pd\r\nimport cv2\r\nimport numpy as np\r\n\r\ndef ocr_table_from_scanned_pdf(pdf_path, page_num=0):\r\n    \"\"\"Extract table from scanned PDF using OCR with table detection\"\"\"\r\n    # Convert specific page to image\r\n    images = convert_from_path(pdf_path, first_page=page_num+1,\r\n                                last_page=page_num+1, dpi=300)\r\n    image = np.array(images[0])\r\n\r\n    # Convert to grayscale\r\n    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\r\n\r\n    # Apply thresholding\r\n    _, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)\r\n\r\n    # Extract text with table structure\r\n    custom_config = r'--oem 3 --psm 6'\r\n    text = pytesseract.image_to_string(gray, config=custom_config)\r\n\r\n    # Parse text into table structure\r\n    lines = text.strip().split('\\n')\r\n    data = [line.split() for line in lines if line.strip()]\r\n\r\n    if data:\r\n        # Assume first row is header\r\n        df = pd.DataFrame(data[1:], columns=data[0] if len(data[0]) > 0 else None)\r\n        return df\r\n    return pd.DataFrame()\r\n\r\n# Usage\r\ndf = ocr_table_from_scanned_pdf(\"scanned_bom.pdf\")\r\nprint(df)\r\n```\r\n\r\n## Construction-Specific Extractions\r\n\r\n### Bill of Materials (BOM) Extraction\r\n\r\n```python\r\nimport pdfplumber\r\nimport pandas as pd\r\nimport re\r\n\r\ndef extract_bom_from_pdf(pdf_path):\r\n    \"\"\"Extract Bill of Materials from construction PDF\"\"\"\r\n    all_items = []\r\n\r\n    with pdfplumber.open(pdf_path) as pdf:\r\n        for page in pdf.pages:\r\n            tables = page.extract_tables()\r\n            for table in tables:\r\n                if not table or len(table) \u003C 2:\r\n                    continue\r\n\r\n                # Find header row (look for common BOM headers)\r\n                header_keywords = ['item', 'description', 'quantity', 'unit', 'material']\r\n                for i, row in enumerate(table):\r\n                    if row and any(keyword in str(row).lower() for keyword in header_keywords):\r\n                        # Found header, process remaining rows\r\n                        headers = [str(h).strip() for h in row]\r\n                        for data_row in table[i+1:]:\r\n                            if data_row and any(cell for cell in data_row if cell):\r\n                                item = dict(zip(headers, data_row))\r\n                                all_items.append(item)\r\n                        break\r\n\r\n    return pd.DataFrame(all_items)\r\n\r\n# Usage\r\nbom = extract_bom_from_pdf(\"project_bom.pdf\")\r\nbom.to_excel(\"bom_extracted.xlsx\", index=False)\r\n```\r\n\r\n### Project Schedule Extraction\r\n\r\n```python\r\nimport pdfplumber\r\nimport pandas as pd\r\nfrom datetime import datetime\r\n\r\ndef extract_schedule_from_pdf(pdf_path):\r\n    \"\"\"Extract project schedule\u002Fgantt data from PDF\"\"\"\r\n    with pdfplumber.open(pdf_path) as pdf:\r\n        all_tasks = []\r\n\r\n        for page in pdf.pages:\r\n            tables = page.extract_tables()\r\n            for table in tables:\r\n                if not table:\r\n                    continue\r\n\r\n                # Look for schedule-like table\r\n                headers = table[0] if table else []\r\n\r\n                # Check if it looks like a schedule\r\n                schedule_keywords = ['task', 'activity', 'start', 'end', 'duration']\r\n                if any(kw in str(headers).lower() for kw in schedule_keywords):\r\n                    for row in table[1:]:\r\n                        if row and any(cell for cell in row if cell):\r\n                            task = dict(zip(headers, row))\r\n                            all_tasks.append(task)\r\n\r\n    df = pd.DataFrame(all_tasks)\r\n\r\n    # Try to parse dates\r\n    date_columns = ['Start', 'End', 'Start Date', 'End Date', 'Finish']\r\n    for col in date_columns:\r\n        if col in df.columns:\r\n            df[col] = pd.to_datetime(df[col], errors='coerce')\r\n\r\n    return df\r\n\r\n# Usage\r\nschedule = extract_schedule_from_pdf(\"project_schedule.pdf\")\r\nprint(schedule)\r\n```\r\n\r\n### Specification Parsing\r\n\r\n```python\r\nimport pdfplumber\r\nimport pandas as pd\r\nimport re\r\n\r\ndef parse_specification_pdf(pdf_path):\r\n    \"\"\"Parse construction specification document\"\"\"\r\n    specs = []\r\n\r\n    with pdfplumber.open(pdf_path) as pdf:\r\n        full_text = \"\"\r\n        for page in pdf.pages:\r\n            text = page.extract_text()\r\n            if text:\r\n                full_text += text + \"\\n\"\r\n\r\n    # Parse sections (common spec format)\r\n    section_pattern = r'(\\d+\\.\\d+(?:\\.\\d+)?)\\s+([A-Z][^\\n]+)'\r\n    sections = re.findall(section_pattern, full_text)\r\n\r\n    for num, title in sections:\r\n        specs.append({\r\n            'section_number': num,\r\n            'title': title.strip(),\r\n            'level': len(num.split('.'))\r\n        })\r\n\r\n    return pd.DataFrame(specs)\r\n\r\n# Usage\r\nspecs = parse_specification_pdf(\"technical_spec.pdf\")\r\nprint(specs)\r\n```\r\n\r\n## Batch Processing\r\n\r\n### Process Multiple PDFs\r\n\r\n```python\r\nimport pdfplumber\r\nimport pandas as pd\r\nfrom pathlib import Path\r\n\r\ndef batch_extract_tables(folder_path, output_folder):\r\n    \"\"\"Process all PDFs in folder and extract tables\"\"\"\r\n    pdf_files = Path(folder_path).glob(\"*.pdf\")\r\n    results = []\r\n\r\n    for pdf_path in pdf_files:\r\n        print(f\"Processing: {pdf_path.name}\")\r\n        try:\r\n            with pdfplumber.open(pdf_path) as pdf:\r\n                for page_num, page in enumerate(pdf.pages):\r\n                    tables = page.extract_tables()\r\n                    for table_num, table in enumerate(tables):\r\n                        if table and len(table) > 1:\r\n                            df = pd.DataFrame(table[1:], columns=table[0])\r\n                            df['_source_file'] = pdf_path.name\r\n                            df['_page'] = page_num + 1\r\n\r\n                            # Save individual table\r\n                            output_name = f\"{pdf_path.stem}_p{page_num+1}_t{table_num+1}.xlsx\"\r\n                            df.to_excel(Path(output_folder) \u002F output_name, index=False)\r\n                            results.append(df)\r\n        except Exception as e:\r\n            print(f\"Error processing {pdf_path.name}: {e}\")\r\n\r\n    # Combined output\r\n    if results:\r\n        combined = pd.concat(results, ignore_index=True)\r\n        combined.to_excel(Path(output_folder) \u002F \"all_tables.xlsx\", index=False)\r\n\r\n    return len(results)\r\n\r\n# Usage\r\ncount = batch_extract_tables(\".\u002Fpdf_documents\u002F\", \".\u002Fextracted\u002F\")\r\nprint(f\"Extracted {count} tables\")\r\n```\r\n\r\n## Data Cleaning After Extraction\r\n\r\n```python\r\nimport pandas as pd\r\n\r\ndef clean_extracted_data(df):\r\n    \"\"\"Clean common issues in PDF-extracted data\"\"\"\r\n    # Remove completely empty rows\r\n    df = df.dropna(how='all')\r\n\r\n    # Strip whitespace from string columns\r\n    for col in df.select_dtypes(include=['object']).columns:\r\n        df[col] = df[col].str.strip()\r\n\r\n    # Remove rows where all cells are empty strings\r\n    df = df[df.apply(lambda row: any(cell != '' for cell in row), axis=1)]\r\n\r\n    # Convert numeric columns\r\n    for col in df.columns:\r\n        # Try to convert to numeric\r\n        numeric_series = pd.to_numeric(df[col], errors='coerce')\r\n        if numeric_series.notna().sum() > len(df) * 0.5:  # More than 50% numeric\r\n            df[col] = numeric_series\r\n\r\n    return df\r\n\r\n# Usage\r\ndf = extract_tables_from_pdf(\"document.pdf\")\r\ndf_clean = clean_extracted_data(df)\r\ndf_clean.to_excel(\"clean_data.xlsx\", index=False)\r\n```\r\n\r\n## Export Options\r\n\r\n```python\r\nimport pandas as pd\r\nimport json\r\n\r\ndef export_to_multiple_formats(df, base_name):\r\n    \"\"\"Export DataFrame to multiple formats\"\"\"\r\n    # Excel\r\n    df.to_excel(f\"{base_name}.xlsx\", index=False)\r\n\r\n    # CSV\r\n    df.to_csv(f\"{base_name}.csv\", index=False, encoding='utf-8-sig')\r\n\r\n    # JSON\r\n    df.to_json(f\"{base_name}.json\", orient='records', indent=2)\r\n\r\n    # JSON Lines (for large datasets)\r\n    df.to_json(f\"{base_name}.jsonl\", orient='records', lines=True)\r\n\r\n# Usage\r\ndf = extract_tables_from_pdf(\"document.pdf\")\r\nexport_to_multiple_formats(df, \"extracted_data\")\r\n```\r\n\r\n## Quick Reference\r\n\r\n| Task | Tool | Code |\r\n|------|------|------|\r\n| Extract table | pdfplumber | `page.extract_table()` |\r\n| Extract text | pdfplumber | `page.extract_text()` |\r\n| OCR scanned | pytesseract | `pytesseract.image_to_string(image)` |\r\n| Merge PDFs | pypdf | `writer.add_page(page)` |\r\n| Convert to image | pdf2image | `convert_from_path(pdf)` |\r\n\r\n## Troubleshooting\r\n\r\n| Issue | Solution |\r\n|-------|----------|\r\n| Table not detected | Try adjusting table settings: `page.extract_table(table_settings={})` |\r\n| Wrong column alignment | Use visual debugging: `page.to_image().draw_rects()` |\r\n| OCR quality poor | Increase DPI, preprocess image, use correct language |\r\n| Memory issues | Process pages one at a time, close PDF after processing |\r\n\r\n## Resources\r\n\r\n- **Book**: \"Data-Driven Construction\" by Artem Boiko, Chapter 2.4\r\n- **Website**: https:\u002F\u002Fdatadrivenconstruction.io\r\n- **pdfplumber Docs**: https:\u002F\u002Fgithub.com\u002Fjsvine\u002Fpdfplumber\r\n- **Tesseract OCR**: https:\u002F\u002Fgithub.com\u002Ftesseract-ocr\u002Ftesseract\r\n\r\n## Next Steps\r\n\r\n- See `image-to-data` for image processing\r\n- See `cad-to-data` for CAD\u002FBIM data extraction\r\n- See `etl-pipeline` for automated processing workflows\r\n- See `data-quality-check` for validating extracted data\r\n","# PDF to Structured Data Conversion\r\n\r\n## Overview\r\n\r\nBased on DDC methodology (Chapter 2.4), this skill transforms unstructured PDF documents into structured formats suitable for analysis and integration. Construction projects generate vast amounts of PDF documentation - specifications, BOMs, schedules, and reports - that need to be extracted and processed.\r\n\r\n**Book Reference:** \"Преобразование данных в структурированную форму\" \u002F \"Data Transformation to Structured Form\"\r\n\r\n> \"Преобразование данных из неструктурированной в структурированную форму — это и искусство, и наука. Этот процесс часто занимает значительную часть работы инженера по обработке данных.\"\r\n> — DDC Book, Chapter 2.4\r\n\r\n## ETL Process Overview\r\n\r\nThe conversion follows the ETL pattern:\r\n1. **Extract**: Load the PDF document\r\n2. **Transform**: Parse and structure the content\r\n3. **Load**: Save to CSV, Excel, or JSON\r\n\r\n## Quick Start\r\n\r\n```python\r\nimport pdfplumber\r\nimport pandas as pd\r\n\r\n# Extract table from PDF\r\nwith pdfplumber.open(\"construction_spec.pdf\") as pdf:\r\n    page = pdf.pages[0]\r\n    table = page.extract_table()\r\n    df = pd.DataFrame(table[1:], columns=table[0])\r\n    df.to_excel(\"extracted_data.xlsx\", index=False)\r\n```\r\n\r\n## Installation\r\n\r\n```bash\r\n# Core libraries\r\npip install pdfplumber pandas openpyxl\r\n\r\n# For scanned PDFs (OCR)\r\npip install pytesseract pdf2image\r\n# Also install Tesseract OCR: https:\u002F\u002Fgithub.com\u002Ftesseract-ocr\u002Ftesseract\r\n\r\n# For advanced PDF operations\r\npip install pypdf\r\n```\r\n\r\n## Native PDF Extraction (pdfplumber)\r\n\r\n### Extract All Tables from PDF\r\n\r\n```python\r\nimport pdfplumber\r\nimport pandas as pd\r\n\r\ndef extract_tables_from_pdf(pdf_path):\r\n    \"\"\"Extract all tables from a PDF file\"\"\"\r\n    all_tables = []\r\n\r\n    with pdfplumber.open(pdf_path) as pdf:\r\n        for page_num, page in enumerate(pdf.pages):\r\n            tables = page.extract_tables()\r\n            for table_num, table in enumerate(tables):\r\n                if table and len(table) > 1:\r\n                    # First row as header\r\n                    df = pd.DataFrame(table[1:], columns=table[0])\r\n                    df['_page'] = page_num + 1\r\n                    df['_table'] = table_num + 1\r\n                    all_tables.append(df)\r\n\r\n    if all_tables:\r\n        return pd.concat(all_tables, ignore_index=True)\r\n    return pd.DataFrame()\r\n\r\n# Usage\r\ndf = extract_tables_from_pdf(\"material_specification.pdf\")\r\ndf.to_excel(\"materials.xlsx\", index=False)\r\n```\r\n\r\n### Extract Text with Layout\r\n\r\n```python\r\nimport pdfplumber\r\n\r\ndef extract_text_with_layout(pdf_path):\r\n    \"\"\"Extract text preserving layout structure\"\"\"\r\n    full_text = []\r\n\r\n    with pdfplumber.open(pdf_path) as pdf:\r\n        for page in pdf.pages:\r\n            text = page.extract_text()\r\n            if text:\r\n                full_text.append(text)\r\n\r\n    return \"\\n\\n--- Page Break ---\\n\\n\".join(full_text)\r\n\r\n# Usage\r\ntext = extract_text_with_layout(\"project_report.pdf\")\r\nwith open(\"report_text.txt\", \"w\", encoding=\"utf-8\") as f:\r\n    f.write(text)\r\n```\r\n\r\n### Extract Specific Table by Position\r\n\r\n```python\r\nimport pdfplumber\r\nimport pandas as pd\r\n\r\ndef extract_table_from_area(pdf_path, page_num, bbox):\r\n    \"\"\"\r\n    Extract table from specific area on page\r\n\r\n    Args:\r\n        pdf_path: Path to PDF file\r\n        page_num: Page number (0-indexed)\r\n        bbox: Bounding box (x0, top, x1, bottom) in points\r\n    \"\"\"\r\n    with pdfplumber.open(pdf_path) as pdf:\r\n        page = pdf.pages[page_num]\r\n        cropped = page.within_bbox(bbox)\r\n        table = cropped.extract_table()\r\n\r\n        if table:\r\n            return pd.DataFrame(table[1:], columns=table[0])\r\n    return pd.DataFrame()\r\n\r\n# Usage - extract table from specific area\r\n# bbox format: (left, top, right, bottom) in points (1 inch = 72 points)\r\ndf = extract_table_from_area(\"drawing.pdf\", 0, (50, 100, 550, 400))\r\n```\r\n\r\n## Scanned PDF Processing (OCR)\r\n\r\n### Extract Text from Scanned PDF\r\n\r\n```python\r\nimport pytesseract\r\nfrom pdf2image import convert_from_path\r\nimport pandas as pd\r\n\r\ndef ocr_scanned_pdf(pdf_path, language='eng'):\r\n    \"\"\"\r\n    Extract text from scanned PDF using OCR\r\n\r\n    Args:\r\n        pdf_path: Path to scanned PDF\r\n        language: Tesseract language code (eng, deu, rus, etc.)\r\n    \"\"\"\r\n    # Convert PDF pages to images\r\n    images = convert_from_path(pdf_path, dpi=300)\r\n\r\n    extracted_text = []\r\n    for i, image in enumerate(images):\r\n        text = pytesseract.image_to_string(image, lang=language)\r\n        extracted_text.append({\r\n            'page': i + 1,\r\n            'text': text\r\n        })\r\n\r\n    return pd.DataFrame(extracted_text)\r\n\r\n# Usage\r\ndf = ocr_scanned_pdf(\"scanned_specification.pdf\", language='eng')\r\ndf.to_csv(\"ocr_results.csv\", index=False)\r\n```\r\n\r\n### OCR Table Extraction\r\n\r\n```python\r\nimport pytesseract\r\nfrom pdf2image import convert_from_path\r\nimport pandas as pd\r\nimport cv2\r\nimport numpy as np\r\n\r\ndef ocr_table_from_scanned_pdf(pdf_path, page_num=0):\r\n    \"\"\"Extract table from scanned PDF using OCR with table detection\"\"\"\r\n    # Convert specific page to image\r\n    images = convert_from_path(pdf_path, first_page=page_num+1,\r\n                                last_page=page_num+1, dpi=300)\r\n    image = np.array(images[0])\r\n\r\n    # Convert to grayscale\r\n    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\r\n\r\n    # Apply thresholding\r\n    _, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)\r\n\r\n    # Extract text with table structure\r\n    custom_config = r'--oem 3 --psm 6'\r\n    text = pytesseract.image_to_string(gray, config=custom_config)\r\n\r\n    # Parse text into table structure\r\n    lines = text.strip().split('\\n')\r\n    data = [line.split() for line in lines if line.strip()]\r\n\r\n    if data:\r\n        # Assume first row is header\r\n        df = pd.DataFrame(data[1:], columns=data[0] if len(data[0]) > 0 else None)\r\n        return df\r\n    return pd.DataFrame()\r\n\r\n# Usage\r\ndf = ocr_table_from_scanned_pdf(\"scanned_bom.pdf\")\r\nprint(df)\r\n```\r\n\r\n## Construction-Specific Extractions\r\n\r\n### Bill of Materials (BOM) Extraction\r\n\r\n```python\r\nimport pdfplumber\r\nimport pandas as pd\r\nimport re\r\n\r\ndef extract_bom_from_pdf(pdf_path):\r\n    \"\"\"Extract Bill of Materials from construction PDF\"\"\"\r\n    all_items = []\r\n\r\n    with pdfplumber.open(pdf_path) as pdf:\r\n        for page in pdf.pages:\r\n            tables = page.extract_tables()\r\n            for table in tables:\r\n                if not table or len(table) \u003C 2:\r\n                    continue\r\n\r\n                # Find header row (look for common BOM headers)\r\n                header_keywords = ['item', 'description', 'quantity', 'unit', 'material']\r\n                for i, row in enumerate(table):\r\n                    if row and any(keyword in str(row).lower() for keyword in header_keywords):\r\n                        # Found header, process remaining rows\r\n                        headers = [str(h).strip() for h in row]\r\n                        for data_row in table[i+1:]:\r\n                            if data_row and any(cell for cell in data_row if cell):\r\n                                item = dict(zip(headers, data_row))\r\n                                all_items.append(item)\r\n                        break\r\n\r\n    return pd.DataFrame(all_items)\r\n\r\n# Usage\r\nbom = extract_bom_from_pdf(\"project_bom.pdf\")\r\nbom.to_excel(\"bom_extracted.xlsx\", index=False)\r\n```\r\n\r\n### Project Schedule Extraction\r\n\r\n```python\r\nimport pdfplumber\r\nimport pandas as pd\r\nfrom datetime import datetime\r\n\r\ndef extract_schedule_from_pdf(pdf_path):\r\n    \"\"\"Extract project schedule\u002Fgantt data from PDF\"\"\"\r\n    with pdfplumber.open(pdf_path) as pdf:\r\n        all_tasks = []\r\n\r\n        for page in pdf.pages:\r\n            tables = page.extract_tables()\r\n            for table in tables:\r\n                if not table:\r\n                    continue\r\n\r\n                # Look for schedule-like table\r\n                headers = table[0] if table else []\r\n\r\n                # Check if it looks like a schedule\r\n                schedule_keywords = ['task', 'activity', 'start', 'end', 'duration']\r\n                if any(kw in str(headers).lower() for kw in schedule_keywords):\r\n                    for row in table[1:]:\r\n                        if row and any(cell for cell in row if cell):\r\n                            task = dict(zip(headers, row))\r\n                            all_tasks.append(task)\r\n\r\n    df = pd.DataFrame(all_tasks)\r\n\r\n    # Try to parse dates\r\n    date_columns = ['Start', 'End', 'Start Date', 'End Date', 'Finish']\r\n    for col in date_columns:\r\n        if col in df.columns:\r\n            df[col] = pd.to_datetime(df[col], errors='coerce')\r\n\r\n    return df\r\n\r\n# Usage\r\nschedule = extract_schedule_from_pdf(\"project_schedule.pdf\")\r\nprint(schedule)\r\n```\r\n\r\n### Specification Parsing\r\n\r\n```python\r\nimport pdfplumber\r\nimport pandas as pd\r\nimport re\r\n\r\ndef parse_specification_pdf(pdf_path):\r\n    \"\"\"Parse construction specification document\"\"\"\r\n    specs = []\r\n\r\n    with pdfplumber.open(pdf_path) as pdf:\r\n        full_text = \"\"\r\n        for page in pdf.pages:\r\n            text = page.extract_text()\r\n            if text:\r\n                full_text += text + \"\\n\"\r\n\r\n    # Parse sections (common spec format)\r\n    section_pattern = r'(\\d+\\.\\d+(?:\\.\\d+)?)\\s+([A-Z][^\\n]+)'\r\n    sections = re.findall(section_pattern, full_text)\r\n\r\n    for num, title in sections:\r\n        specs.append({\r\n            'section_number': num,\r\n            'title': title.strip(),\r\n            'level': len(num.split('.'))\r\n        })\r\n\r\n    return pd.DataFrame(specs)\r\n\r\n# Usage\r\nspecs = parse_specification_pdf(\"technical_spec.pdf\")\r\nprint(specs)\r\n```\r\n\r\n## Batch Processing\r\n\r\n### Process Multiple PDFs\r\n\r\n```python\r\nimport pdfplumber\r\nimport pandas as pd\r\nfrom pathlib import Path\r\n\r\ndef batch_extract_tables(folder_path, output_folder):\r\n    \"\"\"Process all PDFs in folder and extract tables\"\"\"\r\n    pdf_files = Path(folder_path).glob(\"*.pdf\")\r\n    results = []\r\n\r\n    for pdf_path in pdf_files:\r\n        print(f\"Processing: {pdf_path.name}\")\r\n        try:\r\n            with pdfplumber.open(pdf_path) as pdf:\r\n                for page_num, page in enumerate(pdf.pages):\r\n                    tables = page.extract_tables()\r\n                    for table_num, table in enumerate(tables):\r\n                        if table and len(table) > 1:\r\n                            df = pd.DataFrame(table[1:], columns=table[0])\r\n                            df['_source_file'] = pdf_path.name\r\n                            df['_page'] = page_num + 1\r\n\r\n                            # Save individual table\r\n                            output_name = f\"{pdf_path.stem}_p{page_num+1}_t{table_num+1}.xlsx\"\r\n                            df.to_excel(Path(output_folder) \u002F output_name, index=False)\r\n                            results.append(df)\r\n        except Exception as e:\r\n            print(f\"Error processing {pdf_path.name}: {e}\")\r\n\r\n    # Combined output\r\n    if results:\r\n        combined = pd.concat(results, ignore_index=True)\r\n        combined.to_excel(Path(output_folder) \u002F \"all_tables.xlsx\", index=False)\r\n\r\n    return len(results)\r\n\r\n# Usage\r\ncount = batch_extract_tables(\".\u002Fpdf_documents\u002F\", \".\u002Fextracted\u002F\")\r\nprint(f\"Extracted {count} tables\")\r\n```\r\n\r\n## Data Cleaning After Extraction\r\n\r\n```python\r\nimport pandas as pd\r\n\r\ndef clean_extracted_data(df):\r\n    \"\"\"Clean common issues in PDF-extracted data\"\"\"\r\n    # Remove completely empty rows\r\n    df = df.dropna(how='all')\r\n\r\n    # Strip whitespace from string columns\r\n    for col in df.select_dtypes(include=['object']).columns:\r\n        df[col] = df[col].str.strip()\r\n\r\n    # Remove rows where all cells are empty strings\r\n    df = df[df.apply(lambda row: any(cell != '' for cell in row), axis=1)]\r\n\r\n    # Convert numeric columns\r\n    for col in df.columns:\r\n        # Try to convert to numeric\r\n        numeric_series = pd.to_numeric(df[col], errors='coerce')\r\n        if numeric_series.notna().sum() > len(df) * 0.5:  # More than 50% numeric\r\n            df[col] = numeric_series\r\n\r\n    return df\r\n\r\n# Usage\r\ndf = extract_tables_from_pdf(\"document.pdf\")\r\ndf_clean = clean_extracted_data(df)\r\ndf_clean.to_excel(\"clean_data.xlsx\", index=False)\r\n```\r\n\r\n## Export Options\r\n\r\n```python\r\nimport pandas as pd\r\nimport json\r\n\r\ndef export_to_multiple_formats(df, base_name):\r\n    \"\"\"Export DataFrame to multiple formats\"\"\"\r\n    # Excel\r\n    df.to_excel(f\"{base_name}.xlsx\", index=False)\r\n\r\n    # CSV\r\n    df.to_csv(f\"{base_name}.csv\", index=False, encoding='utf-8-sig')\r\n\r\n    # JSON\r\n    df.to_json(f\"{base_name}.json\", orient='records', indent=2)\r\n\r\n    # JSON Lines (for large datasets)\r\n    df.to_json(f\"{base_name}.jsonl\", orient='records', lines=True)\r\n\r\n# Usage\r\ndf = extract_tables_from_pdf(\"document.pdf\")\r\nexport_to_multiple_formats(df, \"extracted_data\")\r\n```\r\n\r\n## Quick Reference\r\n\r\n| Task | Tool | Code |\r\n|------|------|------|\r\n| Extract table | pdfplumber | `page.extract_table()` |\r\n| Extract text | pdfplumber | `page.extract_text()` |\r\n| OCR scanned | pytesseract | `pytesseract.image_to_string(image)` |\r\n| Merge PDFs | pypdf | `writer.add_page(page)` |\r\n| Convert to image | pdf2image | `convert_from_path(pdf)` |\r\n\r\n## Troubleshooting\r\n\r\n| Issue | Solution |\r\n|-------|----------|\r\n| Table not detected | Try adjusting table settings: `page.extract_table(table_settings={})` |\r\n| Wrong column alignment | Use visual debugging: `page.to_image().draw_rects()` |\r\n| OCR quality poor | Increase DPI, preprocess image, use correct language |\r\n| Memory issues | Process pages one at a time, close PDF after processing |\r\n\r\n## Resources\r\n\r\n- **Book**: \"Data-Driven Construction\" by Artem Boiko, Chapter 2.4\r\n- **Website**: https:\u002F\u002Fdatadrivenconstruction.io\r\n- **pdfplumber Docs**: https:\u002F\u002Fgithub.com\u002Fjsvine\u002Fpdfplumber\r\n- **Tesseract OCR**: https:\u002F\u002Fgithub.com\u002Ftesseract-ocr\u002Ftesseract\r\n\r\n## Next Steps\r\n\r\n- See `image-to-data` for image processing\r\n- See `cad-to-data` for CAD\u002FBIM data extraction\r\n- See `etl-pipeline` for automated processing workflows\r\n- See `data-quality-check` for validating extracted data\r\n",{"slug":5,"description":7,"display_name":39},"PDF To Structured","main","e7e336ac628c3e3bd771aff1aaa469c93778f94a","skills\u002Fdatadrivenconstruction\u002Fpdf-to-structured",0,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del","2026-08-23 22:39:37",{"source":8,"skillName":5,"commands":48,"prompt":58,"zipAvailable":59},[49,52,55],{"tool":50,"command":51},"npx","npx skills add kbarbel640-del\u002Fskills --skill pdf-to-structured",{"tool":53,"command":54},"bunx","bunx skills add kbarbel640-del\u002Fskills --skill pdf-to-structured",{"tool":56,"command":57},"pnpm","pnpm dlx skills add kbarbel640-del\u002Fskills --skill pdf-to-structured","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fdatadrivenconstruction\u002Fpdf-to-structured\u002FSKILL.md",true,[61],{"path":62,"resourceType":63,"resourceTypeDesc":64,"sizeBytes":65,"sourceHtmlUrl":66},"_meta.json","REFERENCE","参考文档",302,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fdatadrivenconstruction\u002Fpdf-to-structured\u002F_meta.json",[68,94,117,135,140,160],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":34},"01M6G8J55967D6281ACMKAKTEQ","crowd-prompting","A marketplace where AI agents improve prompts, system instructions, tool descriptions, and other text-based content with domain expertise from real-world operations — and earn tokens for valuable contributions.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzzadrian\u002Fcrowd-prompting\u002FSKILL.md",[],[75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93],"crowd prompting","prompting","api","with","tokens","domain","world","prompts","operations","instructions","text","tool","system","improve","productivity","marketplace","https","content","ai agents",{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":34},"01M6G8J0PKPAYVET6BWE8W4C26","dilemm-ai","Compete in DilemmAI, the prisoner's dilemma AI arena at dilemm.ai. Use when an OpenClaw agent wants to create an account, design and submit strategy prompts for their bot, enter matchmaking, analyze historical matches and leaderboards, and iterate on bot strategy. Requires headless browser automation (no API available yet).","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzyori\u002Fdilemm-ai\u002FSKILL.md",[],[101,77,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,82,30],"dilemm ai","arena","analyze","browser","openclaw agent","create","automation","browser automation","bot","openclaw","design","strategy","headless","compete","submit","matchmaking",{"skillNo":118,"name":119,"nameZh":6,"description":120,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":121,"categories":122,"keywords":123,"publishedAt":34},"01M6G8HWAF3K9SW7NP3Z83CPJ6","arxiv-paper-reviews","Interact with arXiv Crawler API to fetch papers, read reviews, and submit comments. Use when working with arXiv papers, fetching paper lists by date\u002Fcategory\u002Finterest, viewing paper details with comments, or submitting paper reviews via API at http:\u002F\u002F150.158.152.82:8000.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzxrys\u002Fweak-accept\u002FSKILL.md",[],[124,125,126,127,128,129,130,78,131,115,30,132,77,133,134],"arxiv paper reviews","reviews","arxiv","paper","crawler","papers","comments","fetch","read","http","via",{"skillNo":136,"name":119,"nameZh":6,"description":120,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":137,"categories":138,"keywords":139,"publishedAt":34},"01M6G8HQJ7N7WMY6YV7D7SSJ16","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzxrys\u002Farxiv-paper-reviews\u002FSKILL.md",[],[127,126,125,124,134,129,130,78,128,115,30,131,132,77,133],{"skillNo":141,"name":142,"nameZh":6,"description":143,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":144,"categories":145,"keywords":146,"publishedAt":34},"01M6G8HM95Y64JNVFC2HN4E2BG","git-summary","Get a quick summary of the current Git repository including status, recent commits, branches, and contributors.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzweack\u002Fgit-summary\u002FSKILL.md",[],[147,148,149,150,151,152,153,154,155,156,157,158,159],"git","summary","git summary","commits","repository","win32","status","linux","contributors","true","quick","get","branches",{"skillNo":161,"name":162,"nameZh":6,"description":163,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":164,"categories":165,"keywords":166,"publishedAt":34},"01M6G8HGEGF05CNEJCGVYFSC4R","agent-constitution","Interact with AgentConstitution governance contracts on Base Sepolia. Check compliance, read rules, log actions, query governance state.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fztsalexey\u002Fagent-constitution\u002FSKILL.md",[],[167,168,169,170,78,171,172,40,173,132,174,175,176,177,178,91,179,180,181],"agent constitution","constitution","contracts","tree","query","base","log","check","Rules","projects","compliance","actions","state","governance","github"]