python Copy code
import sys
from bs4 import BeautifulSoup
import argparse
def process_svg_for_rects(svg_element):
rect_data = {'w35': "NONE", 'x35': "NONE", 'w10': "NONE", 'x10': "NONE"}
if not svg_element:
return rect_data
rects = svg_element.find_all('rect')
for rect in rects:
next_text = rect.find_next('text')
if next_text:
text_content = next_text.get_text(strip=True)
if text_content == "-35":
rect_data['w35'] = rect.get('width', "NONE")
rect_data['x35'] = rect.get('x', "NONE")
elif text_content == "-10":
rect_data['w10'] = rect.get('width', "NONE")
rect_data['x10'] = rect.get('x', "NONE")
return rect_data
def main():
parser = argparse.ArgumentParser(description="Extract data from HTML tables and associated SVGs to a TSV file.")
parser.add_argument("--input", default='table.html', help="Path to the input HTML file (default: table.html)")
parser.add_argument("--output", default='table.tsv', help="Path to the output TSV file (default: table.tsv)")
args = parser.parse_args()
html_file_path = args.input
tsv_file_path = args.output
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)
output_tsv_lines = []
html_tables = soup.find_all('table')
if not html_tables:
print("No <table> elements found.", file=sys.stderr)
sys.exit(1)
for html_table_element in html_tables:
final_table_headers = []
output_data_entries = []
max_cols_in_html_table = 0
html_table_rows = html_table_element.find_all('tr')
is_first_tr_being_processed = True
for tr_element in html_table_rows:
current_row_cells_text = []
is_current_tr_a_header_row = False
cells = tr_element.find_all(['th', 'td'])
svg_element_in_row = None
for svg_tag in tr_element.find_all('svg'):
if svg_tag.get('width') == '648' and svg_tag.get('height') == '50':
svg_element_in_row = svg_tag
break
current_row_rect_data = process_svg_for_rects(svg_element_in_row)
if not cells:
output_data_entries.append(([], current_row_rect_data))
is_first_tr_being_processed = False
continue
for cell_element in cells:
if cell_element.name == 'th':
is_current_tr_a_header_row = True
cell_text = cell_element.get_text(separator=" ", strip=True)
cell_text = cell_text.replace('\n', ' ').replace('\r', '').replace('\t', ' ')
current_row_cells_text.append(cell_text)
if is_first_tr_being_processed and is_current_tr_a_header_row:
final_table_headers = list(current_row_cells_text)
max_cols_in_html_table = len(final_table_headers)
else:
if is_first_tr_being_processed:
final_table_headers = [''] * len(current_row_cells_text)
max_cols_in_html_table = len(current_row_cells_text)
output_data_entries.append((current_row_cells_text, current_row_rect_data))
max_cols_in_html_table = max(max_cols_in_html_table, len(current_row_cells_text))
if len(final_table_headers) < max_cols_in_html_table:
final_table_headers.extend([''] * (max_cols_in_html_table - len(final_table_headers)))
is_first_tr_being_processed = False
combined_tsv_headers = list(final_table_headers)
combined_tsv_headers.extend(["width-35", "x-35", "width-10", "x-10"])
output_tsv_lines.append('\t'.join(combined_tsv_headers))
for html_cell_list, rect_data_dict in output_data_entries:
current_output_row_parts = []
current_output_row_parts.extend(html_cell_list)
if len(html_cell_list) < max_cols_in_html_table:
current_output_row_parts.extend([''] * (max_cols_in_html_table - len(html_cell_list)))
w35_val = rect_data_dict.get('w35', "NONE")
x35_val = rect_data_dict.get('x35', "NONE")
w10_val = rect_data_dict.get('w10', "NONE")
x10_val = rect_data_dict.get('x10', "NONE")
current_output_row_parts.extend([str(w35_val), str(x35_val), str(w10_val), str(x10_val)])
output_tsv_lines.append('\t'.join(current_output_row_parts))
if not output_tsv_lines:
with open(tsv_file_path, 'w', encoding='utf-8') as f:
pass
print(f"Created empty file '{tsv_file_path}' (no content generated).")
else:
while output_tsv_lines and output_tsv_lines[-1] == "":
output_tsv_lines.pop()
try:
with open(tsv_file_path, 'w', encoding='utf-8') as f:
if output_tsv_lines:
f.write('\n'.join(output_tsv_lines))
f.write('\n')
print(f"Successfully wrote to '{tsv_file_path}'.")
except Exception as e:
print(f"Error writing output file: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()