Предотвращение потери данных при деплое: batch_v3, search_engine, xlsx_utils, тесты, скрипты деплоя, архитектура, security page, admin page. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
112 lines
4.5 KiB
Python
112 lines
4.5 KiB
Python
"""Shared utilities for xlsx/zip processing across batch modules."""
|
|
|
|
import zipfile
|
|
import xml.etree.ElementTree as ET
|
|
from pathlib import Path
|
|
|
|
|
|
def read_xlsx_xml(path: str, max_rows: int = 50) -> dict:
|
|
"""Read xlsx via XML (handles broken styles). Returns {sheet_name: [[row], ...]}."""
|
|
result = {}
|
|
try:
|
|
z = zipfile.ZipFile(path)
|
|
ns = {'s': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'}
|
|
# Shared strings
|
|
strings = []
|
|
try:
|
|
ss = ET.parse(z.open('xl/sharedStrings.xml')).getroot()
|
|
for si in ss.findall('.//s:si', ns):
|
|
strings.append(''.join(t.text or '' for t in si.findall('.//s:t', ns)))
|
|
except KeyError:
|
|
pass
|
|
# Sheet names and rels
|
|
wb = ET.parse(z.open('xl/workbook.xml')).getroot()
|
|
rels = ET.parse(z.open('xl/_rels/workbook.xml.rels')).getroot()
|
|
rid_map = {}
|
|
for r in rels.iter():
|
|
rid = r.get('Id', '')
|
|
tgt = r.get('Target', '')
|
|
if rid and tgt:
|
|
rid_map[rid] = tgt
|
|
|
|
for sheet in wb.findall('.//s:sheet', ns):
|
|
name = sheet.get('name', '')
|
|
rid = sheet.attrib.get('{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id', '')
|
|
target = rid_map.get(rid, '')
|
|
if not target:
|
|
continue
|
|
if target.startswith('/'):
|
|
sheet_path = target.lstrip('/')
|
|
elif target.startswith('xl/'):
|
|
sheet_path = target
|
|
else:
|
|
sheet_path = f'xl/{target}'
|
|
try:
|
|
sheet_xml = ET.parse(z.open(sheet_path)).getroot()
|
|
except KeyError:
|
|
continue
|
|
rows = []
|
|
for row_el in sheet_xml.findall('.//s:row', ns):
|
|
row_num = int(row_el.get('r', len(rows) + 1))
|
|
while len(rows) < row_num - 1:
|
|
rows.append([])
|
|
if len(rows) >= max_rows:
|
|
break
|
|
row_data = [''] * 26 # A-Z
|
|
for c in row_el.findall('s:c', ns):
|
|
ref = c.get('r', '')
|
|
cell_type = c.get('t', '')
|
|
v = c.find('s:v', ns)
|
|
val = v.text if v is not None else ''
|
|
if cell_type == 's' and val.isdigit():
|
|
idx = int(val)
|
|
val = strings[idx] if idx < len(strings) else val
|
|
elif cell_type == 'inlineStr':
|
|
is_el = c.find('s:is', ns)
|
|
if is_el is not None:
|
|
val = ''.join(t.text or '' for t in is_el.findall('.//s:t', ns))
|
|
col_letters = ''.join(ch for ch in ref if ch.isalpha())
|
|
col_idx = 0
|
|
for ch in col_letters.upper():
|
|
col_idx = col_idx * 26 + (ord(ch) - ord('A'))
|
|
if col_idx < len(row_data):
|
|
row_data[col_idx] = val
|
|
while row_data and row_data[-1] == '':
|
|
row_data.pop()
|
|
rows.append(row_data)
|
|
result[name] = rows
|
|
z.close()
|
|
except Exception as e:
|
|
result['_error'] = str(e)
|
|
return result
|
|
|
|
|
|
def extract_zip(zip_path: str, dest_dir: str) -> list[str]:
|
|
"""Extract zip and return list of xlsx/gge/esw files.
|
|
|
|
Handles Cyrillic filenames: Python's zipfile decodes names as CP437
|
|
when the UTF-8 flag is not set. We detect and fix this.
|
|
"""
|
|
with zipfile.ZipFile(zip_path) as z:
|
|
for info in z.infolist():
|
|
if not (info.flag_bits & 0x800):
|
|
# Try CP437→UTF-8 first, then CP437→CP866 (Windows Russian OEM)
|
|
for target_enc in ('utf-8', 'cp866'):
|
|
try:
|
|
fixed = info.filename.encode('cp437').decode(target_enc)
|
|
info.filename = fixed
|
|
break
|
|
except (UnicodeDecodeError, UnicodeEncodeError):
|
|
continue
|
|
basename = Path(info.filename).name
|
|
if basename.startswith('._') or '__MACOSX' in info.filename:
|
|
continue
|
|
z.extract(info, dest_dir)
|
|
SMETA_EXTENSIONS = {'.xlsx', '.xls', '.gge', '.esw', '.xml'}
|
|
files = []
|
|
for f in Path(dest_dir).rglob('*'):
|
|
if f.is_file() and f.suffix.lower() in SMETA_EXTENSIONS \
|
|
and not f.name.startswith('~$') and not f.name.startswith('._'):
|
|
files.append(str(f))
|
|
return sorted(files)
|