Full code!
- User
Full code!
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Full code!
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's the full, corrected code that includes:
<rect> elements that are nested within <text> elements in <svg>s of specific dimensions (width="648" and height="50")<text> elements (e.g., "-35" and "-10")"NONE"import sys
from bs4 import BeautifulSoup
html_file_path = 'table.html'
tsv_file_path = 'table.tsv'
def process_svg_for_rects(svg_element):
"""
Process an SVG element to extract rect data associated with "-35" and "-10" text.
Returns a dictionary with keys: w35, x35, w10, x10
"""
rect_data = {'w35': "NONE", 'x35': "NONE", 'w10': "NONE", 'x10': "NONE"}
# Find all rect elements in the SVG
rects = svg_element.find_all('rect')
for rect in rects:
# Look for the next text element that contains "-35" or "-10"
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
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 table_idx, html_table_element in enumerate(html_tables):
if len(html_tables) > 1:
output_tsv_lines.append(f"# --- Data from Table {table_idx + 1} ---")
else:
output_tsv_lines.append(f"# --- Combined Table and Rect Data ---")
table_headers_html = []
table_data_rows_html = []
rect_data_per_html_row = []
html_table_rows = html_table_element.find_all('tr')
is_first_row = True
current_num_html_cols = 0
for tr_element in html_table_rows:
current_row_cells_text = []
is_header_row_tr = False
# Extract cell data
cells = tr_element.find_all(['th', 'td'])
if not cells:
rect_data_per_html_row.append({
'w35': "NONE", 'x35': "NONE",
'w10': "NONE", 'x10': "NONE"
})
table_data_rows_html.append([])
continue
for cell_element in cells:
if cell_element.name == 'th':
is_header_row_tr = 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_row:
if is_header_row_tr:
table_headers_html = list(current_row_cells_text)
else:
table_headers_html = [''] * len(current_row_cells_text)
table_data_rows_html.append(current_row_cells_text)
current_num_html_cols = len(table_headers_html)
is_first_row = False
else:
table_data_rows_html.append(current_row_cells_text)
current_num_html_cols = max(current_num_html_cols, len(current_row_cells_text))
if len(table_headers_html) < current_num_html_cols:
table_headers_html.extend([''] * (current_num_html_cols - len(table_headers_html)))
# Process SVG with specific dimensions
svg_element_in_row = None
for svg in tr_element.find_all('svg'):
if svg.get('width') == '648' and svg.get('height') == '50':
svg_element_in_row = svg
break
if svg_element_in_row:
rect_data = process_svg_for_rects(svg_element_in_row)
else:
rect_data = {'w35': "NONE", 'x35': "NONE", 'w10': "NONE", 'x10': "NONE"}
rect_data_per_html_row.append(rect_data)
# Combine headers
combined_tsv_headers = list(table_headers_html)
combined_tsv_headers.extend(["width-35", "x-35", "width-10", "x-10"])
output_tsv_lines.append('\t'.join(combined_tsv_headers))
# Create output rows with 2-row shift for rect data
num_html_data_rows = len(table_data_rows_html)
num_output_data_rows = max(num_html_data_rows, len(rect_data_per_html_row) + 2)
for i in range(num_output_data_rows):
current_output_row_parts = []
# HTML table part
if i < num_html_data_rows:
html_part = table_data_rows_html[i]
current_output_row_parts.extend(html_part)
current_output_row_parts.extend([''] * (current_num_html_cols - len(html_part)))
else:
current_output_row_parts.extend([''] * current_num_html_cols)
# Rect data part (shifted by 2 rows)
rect_data_source_idx = i - 2
w35_val, x35_val, w10_val, x10_val = "", "", "", ""
if rect_data_source_idx >= 0 and rect_data_source_idx < len(rect_data_per_html_row):
rect_set = rect_data_per_html_row[rect_data_source_idx]
w35_val = rect_set['w35']
x35_val = rect_set['x35']
w10_val = rect_set['w10']
x10_val = rect_set['x10']
current_output_row_parts.extend([w35_val, x35_val, w10_val, x10_val])
output_tsv_lines.append('\t'.join(current_output_row_parts))
output_tsv_lines.append("")
# Write output
if not output_tsv_lines:
with open(tsv_file_path, 'w', encoding='utf-8'): pass
print(f"Created empty file '{tsv_file_path}'.")
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:
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)
<rect> and <text> handling: Uses find_next('text') to correctly locate text elements even if they are nested inside other tags.<svg> elements with width="648" and height="50"."NONE".Given your sample SVG:
<svg width="648" height="50">
<text>
<rect width="48" height="15" x="392" y="20" />
<text>-10</text>
<rect width="48" height="15" x="224" y="20" />
<text>-35</text>
</text>
</svg>
The TSV will have:
... ... 48 392 48 224
For the corresponding HTML table row, shifted by 2 rows.
Let me know if you'd like to add support for more text patterns or adjust the formatting further!