import sys
from bs4 import BeautifulSoup
html_file_path = 'table.html'
tsv_file_path = 'table.tsv'
try:
with open(html_file_path, 'r', encoding='utf-8') as f:
html_content = f.read()
except FileNotFoundError:
print(f"Error: Input file '{html_file_path}' not found.", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Error reading file '{html_file_path}': {e}", file=sys.stderr)
sys.exit(1)
try:
soup = BeautifulSoup(html_content, 'lxml')
except Exception as e:
print(f"Error parsing HTML: {e}", file=sys.stderr)
sys.exit(1)
# Extract rect data
rects_minus_35 = []
rects_minus_10 = []
for rect in soup.find_all('rect'):
info = {'width': rect.get('width', ''), 'x': rect.get('x', '')}
txt = rect.find_next_sibling('text')
if txt:
t = txt.get_text(strip=True)
if t == "-35":
rects_minus_35.append(info)
elif t == "-10":
rects_minus_10.append(info)
tsv_lines = []
tables = soup.find_all('table')
if tables:
for ti, table in enumerate(tables):
header_label = f"# --- Combined Table {ti+1} and Rect Data ---"
tsv_lines.append(header_label)
# Extract headers and rows
rows = table.find_all('tr')
html_headers = []
html_rows = []
num_html_cols = 0
first = True
for r in rows:
cells = r.find_all(['th', 'td'])
texts = [c.get_text(" ", strip=True).replace('\t',' ') for c in cells]
if first:
if r.find('th'):
html_headers = texts[:]
else:
html_headers = [''] * len(texts)
html_rows.append(texts)
num_html_cols = len(html_headers)
first = False
else:
html_rows.append(texts)
num_html_cols = max(num_html_cols, len(texts))
if not html_headers:
num_html_cols = max(len(r) for r in html_rows) if html_rows else 0
html_headers = [''] * num_html_cols
# Build combined header
combined = html_headers[:]
if rects_minus_35 or rects_minus_10:
combined += ["width-35", "x-35", "width-10", "x-10"]
tsv_lines.append("\t".join(combined))
# Determine number of rows (with 2-row shift for rects)
max_html = len(html_rows)
max_r35 = len(rects_minus_35)
max_r10 = len(rects_minus_10)
max_rows = max(max_html, max_r35, max_r10) + 2
for i in range(max_rows):
row_parts = []
# HTML part
if i < max_html:
part = html_rows[i]
row_parts.extend(part + ['']*(num_html_cols-len(part)))
else:
row_parts.extend(['']*num_html_cols)
# Rects shifted down by 2 rows
if rects_minus_35 or rects_minus_10:
if i >= 2 and (i-2) < max_r35:
row_parts.append(rects_minus_35[i-2]['width'])
row_parts.append(rects_minus_35[i-2]['x'])
else:
row_parts.extend(['',''])
if i >= 2 and (i-2) < max_r10:
row_parts.append(rects_minus_10[i-2]['width'])
row_parts.append(rects_minus_10[i-2]['x'])
else:
row_parts.extend(['',''])
tsv_lines.append("\t".join(row_parts))
tsv_lines.append("")
elif rects_minus_35 or rects_minus_10:
tsv_lines.append("# --- Rect Data Only ---")
tsv_lines.append("width-35\tx-35\twidth-10\tx-10")
max_r35 = len(rects_minus_35)
max_r10 = len(rects_minus_10)
max_rows = max(max_r35, max_r10)
for i in range(max_rows):
parts = []
if i < max_r35:
parts += [rects_minus_35[i]['width'], rects_minus_35[i]['x']]
else:
parts += ['', '']
if i < max_r10:
parts += [rects_minus_10[i]['width'], rects_minus_10[i]['x']]
else:
parts += ['', '']
tsv_lines.append("\t".join(parts))
tsv_lines.append("")
else:
print("No table or rect data found.", file=sys.stderr)
# Write output
if not tsv_lines:
with open(tsv_file_path, 'w', encoding='utf-8'): pass
print(f"Created empty file '{tsv_file_path}'.")
else:
# Trim trailing blanks
while tsv_lines and tsv_lines[-1] == "":
tsv_lines.pop()
with open(tsv_file_path, 'w', encoding='utf-8') as f:
f.write("\n".join(tsv_lines))
f.write("\n")
print(f"Successfully wrote to '{tsv_file_path}'.")