Spaces:
Runtime error
Runtime error
File size: 10,358 Bytes
7bd9199 f66027e 266e2a4 7bd9199 f66027e cf34c19 7bd9199 dc472fa 7bd9199 dc472fa 7bd9199 dc472fa 7bd9199 dc472fa 7bd9199 dc472fa 7bd9199 dc472fa 7bd9199 dc472fa 7bd9199 dc472fa 7bd9199 ab6174c 266e2a4 ab6174c 266e2a4 ab6174c 266e2a4 ab6174c 266e2a4 cf34c19 266e2a4 7bd9199 |
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 |
import asyncio
import io
import json
import os
import uuid
import fitz
from openpyxl import load_workbook
import markdown2
import subprocess
from pathlib import Path
class FileClient:
def __init__(self):
pass
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_value, traceback):
pass
async def extract_from_pdf(self, file_bytes: io.BytesIO):
doc = fitz.open(stream=file_bytes, filetype="pdf")
layout_data = {
"metadata": doc.metadata,
"page_count": len(doc),
"pages": []
}
all_headers = []
all_footers = []
for page_num, page in enumerate(doc):
blocks = page.get_text("dict")["blocks"]
page_content = []
text_blocks = []
header_blocks = []
footer_blocks = []
body_blocks = []
page_rect = page.rect
media_box = page.mediabox if hasattr(page, 'mediabox') else page_rect
crop_box = page.cropbox
header_region = (page_rect.y0, page_rect.y0 + (page_rect.height * 0.2))
footer_region = (page_rect.y1 - (page_rect.height * 0.2), page_rect.y1)
for block in blocks:
if "lines" in block and block.get("bbox"):
block_bbox = block["bbox"]
is_header = block_bbox[1] >= header_region[0] and block_bbox[3] <= header_region[1]
is_footer = block_bbox[1] >= footer_region[0] and block_bbox[3] <= footer_region[1]
if is_header:
header_blocks.append(block_bbox)
elif is_footer:
footer_blocks.append(block_bbox)
else:
body_blocks.append(block_bbox)
text_blocks.append(block_bbox)
for line in block["lines"]:
for span in line["spans"]:
content_item = {
"text": span["text"],
"font": span["font"],
"size": span["size"],
"color": span.get("color", None),
"flags": span.get("flags", None),
"is_header": is_header,
"is_footer": is_footer
}
page_content.append(content_item)
if body_blocks:
min_x = min(block[0] for block in body_blocks)
min_y = min(block[1] for block in body_blocks)
max_x = max(block[2] for block in body_blocks)
max_y = max(block[3] for block in body_blocks)
margin_left = (min_x - page_rect.x0) / 72
margin_top = (min_y - page_rect.y0) / 72
margin_right = (page_rect.x1 - max_x) / 72
margin_bottom = (page_rect.y1 - max_y) / 72
else:
margin_left = margin_top = margin_right = margin_bottom = 0
crop_margin_left = (crop_box.x0 - media_box.x0) / 72
crop_margin_top = (crop_box.y0 - media_box.y0) / 72
crop_margin_right = (media_box.x1 - crop_box.x1) / 72
crop_margin_bottom = (media_box.y1 - crop_box.y1) / 72
header_height = 0
footer_height = 0
if header_blocks:
header_min_y = min(block[1] for block in header_blocks)
header_max_y = max(block[3] for block in header_blocks)
header_height = (header_max_y - header_min_y) / 72
if footer_blocks:
footer_min_y = min(block[1] for block in footer_blocks)
footer_max_y = max(block[3] for block in footer_blocks)
footer_height = (footer_max_y - footer_min_y) / 72
header_text = ""
footer_text = ""
for item in page_content:
if item["is_header"]:
header_text += item["text"] + " "
elif item["is_footer"]:
footer_text += item["text"] + " "
header_text = header_text.strip()
footer_text = footer_text.strip()
if header_text:
all_headers.append(header_text)
if footer_text:
all_footers.append(footer_text)
page_data = {
"page_number": page_num + 1,
"width": page_rect.width,
"height": page_rect.height,
"margin_top": f"{round(margin_top, 1)} inches",
"margin_left": f"{round(margin_left, 1)} inches",
"margin_right": f"{round(margin_right, 1)} inches",
"margin_bottom": f"{round(margin_bottom, 1)} inches",
"header_height": f"{header_height} inches",
"footer_height": f"{footer_height} inches",
"has_header": len(header_blocks) > 0,
"has_footer": len(footer_blocks) > 0,
"content": page_content
}
if page_num == 0:
page_data["is_first_page"] = True
layout_data["pages"].append(page_data)
if all_headers:
unique_headers = set(all_headers)
layout_data["header_analysis"] = {
"total_pages_with_headers": len(all_headers),
"unique_headers": len(unique_headers),
"is_header_consistent": len(unique_headers) == 1 if all_headers else False
}
if all_footers:
unique_footers = set(all_footers)
layout_data["footer_analysis"] = {
"total_pages_with_footers": len(all_footers),
"unique_footers": len(unique_footers),
"is_footer_consistent": len(unique_footers) == 1 if all_footers else False
}
return layout_data
async def extrcat_from_word(self, file_bytes: io.BytesIO):
data = {
"file_type": "Word Document"
}
file_id = str(uuid.uuid4())
work_dir = f"/files/{file_id}"
os.makedirs(work_dir, exist_ok=True)
docx_path = os.path.join(work_dir, "input.docx")
pdf_path = os.path.join(work_dir, "input.pdf")
try:
with open(docx_path, "wb") as f:
f.write(file_bytes.getvalue())
env = os.environ.copy()
env.update({
"HOME": work_dir,
"UserInstallation": f"file://{work_dir}",
"SAL_USE_VCLPLUGIN": "svp"
})
cmd = [
"libreoffice",
"--headless",
"--nologo",
"--nofirststartwizard",
"--convert-to", "pdf",
"--outdir", work_dir,
docx_path
]
await asyncio.to_thread(
subprocess.run,
cmd,
check=True,
capture_output=True,
env=env
)
with open(pdf_path, "rb") as f:
pdf_bytes = io.BytesIO(f.read())
data["data"] = await self.extract_from_pdf(file_bytes=pdf_bytes)
return data
finally:
for file_path in [docx_path, pdf_path]:
if os.path.exists(file_path):
os.remove(file_path)
async def extract_from_excel(self, file_bytes: io.BytesIO):
wb = load_workbook(file_bytes, data_only=True)
sheets_data = []
for sheet in wb.worksheets:
sheet_info = {
"sheet_name": sheet.title,
"cells": []
}
for row in sheet.iter_rows():
for cell in row:
if cell.value is None:
continue
cell_info = {
"coordinate": cell.coordinate,
"value": cell.value,
}
if cell.font:
if cell.font.name:
cell_info["font_name"] = cell.font.name
if cell.font.size:
cell_info["font_size"] = cell.font.size
if cell.font.bold:
cell_info["bold"] = True
if cell.font.italic:
cell_info["italic"] = True
if cell.font.underline:
cell_info["underline"] = True
if cell.alignment:
if cell.alignment.horizontal:
cell_info["horizontal_align"] = cell.alignment.horizontal
if cell.alignment.vertical:
cell_info["vertical_align"] = cell.alignment.vertical
if cell.alignment.wrap_text:
cell_info["wrap_text"] = True
if cell.fill and cell.fill.start_color and cell.fill.start_color.rgb:
color = cell.fill.start_color.rgb
if color != "00000000":
cell_info["fill_color"] = color
cell_info = {k: v for k, v in cell_info.items() if v is not None}
sheet_info["cells"].append(cell_info)
sheets_data.append(sheet_info)
final_data = {
"sheets": sheets_data
}
return final_data
async def extract_from_json(self, file_bytes: io.BytesIO):
data = json.load(file_bytes)
return data
async def extrcat_from_md(self, file_bytes: io.BytesIO):
data = {
"file_type": "Markdown"
}
md_bytes = file_bytes.getvalue().decode("utf-8")
data["data"] = markdown2.markdown(md_bytes)
return data
async def extract_from_txt(self, file_bytes: io.BytesIO):
data = file_bytes.getvalue().decode("utf-8")
return data
async def extract_from_csv(self, file_bytes: io.BytesIO):
data = file_bytes.getvalue().decode("utf-8")
return data |