import csv import html import sys page_css = """ body { font-family: consolas, monospace; } table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid black; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } tr:nth-child(even) { background-color: #fdfdfd; } """ def csv_to_html(csv_input: str) -> str: """ Converts TSV input from stdin to an HTML table. Args: csv_input: The TSV input as a string. Returns: A string containing the HTML table, or None if an error occurs. """ try: delimiter = "\t" if "\t" in csv_input else "," reader = csv.reader(csv_input.splitlines(), delimiter=delimiter) header = next(reader) # Get the header row header_html = f'{"".join(f"{html.escape(col)}" for col in header)}' rows = [f"{''.join(f'{html.escape(cell)}' for cell in row)}" for row in reader] rows_html = "\n".join(rows) rendered = f""" Query Results {header_html} {rows_html}
""" return rendered except csv.Error as e: raise ValueError(f"Error parsing TSV: {e}") except StopIteration: return "

No data found in TSV input.

" def main(): try: tsv_data = sys.stdin.read() html_output = csv_to_html(tsv_data) if html_output: print(html_output) except UnicodeDecodeError as e: raise ValueError(f"Error decoding input: {e}. Ensure your TSV data is encoded correctly (e.g., UTF-8).") except Exception as e: raise Exception(f"An unexpected error occurred: {e}") if __name__ == "__main__": main()