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 is the full and corrected code with the updated logic for processing the <svg> elements, including handling nested structures correctly:
import sys
from bs4 import BeautifulSoup
html_file_path = 'table.html'
tsv_file_path = 'table.tsv'
# Function to process SVGs and extract rect data
def process_svg_for_rects(svg_element):
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:
# Read the HTML file
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:
# Parse the HTML content
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)
process_svg_for_rects Function:
rect data (width and x) associated with -35 and -10.find_next('text') to locate the <text> elements containing -35 or -10, regardless of nesting.'w35', 'x35', 'w10', 'x10'.SVG Processing:
<svg> elements with width="648" and height="50".<svg> is found, it appends "NONE" for all rect values.HTML Table Rows:
<th> and <td> elements.current_num_html_cols) to ensure proper alignment.Rect Data Alignment:
TSV Output:
width-35, x-35, width-10, x-10).Given your example SVG:
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svgjs="http://svgjs.dev/svgjs" width="648" height="50" id=":rj:">
<text font-size="14px" font-family="'Courier New',Courier,monospace" x="0" y="31.25">
<rect width="48" height="15" x="392" y="20" fill="none" stroke-width="1" stroke="#000000"></rect>
<text font-size="14px" font-family="'Courier New',Courier,monospace" x="401" y="44.25"><tspan dy="0" x="401">-10</tspan></text>
<rect width="48" height="15" x="224" y="20" fill="none" stroke-width="1" stroke="#000000"></rect>
<text font-size="14px" font-family="'Courier New',Courier,monospace" x="233" y="44.25"><tspan dy="0" x="233">-35</tspan></text>
</text>
</svg>
The output TSV will look like this (assuming some HTML table data):
| Col1 | Col2 | Col3 | width-35 | x-35 | width-10 | x-10 |
|---|---|---|---|---|---|---|
| A | B | C | ||||
| D | E | F | ||||
| 48 | 224 | 48 | 392 |
This implementation ensures that the nested structure of your SVG is handled correctly, and the rect data is properly aligned with the HTML table rows. Let me know if you encounter any further issues!