88 lines
2.0 KiB
Python
88 lines
2.0 KiB
Python
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"<th>{html.escape(col)}</th>" for col in header)}'
|
|
rows = [f"<tr>{''.join(f'<td>{html.escape(cell)}</td>' for cell in row)}</tr>" for row in reader]
|
|
rows_html = "\n".join(rows)
|
|
|
|
rendered = f"""
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>Query Results</title>
|
|
<style>{page_css}</style>
|
|
</head>
|
|
<body>
|
|
<table>
|
|
<thead>
|
|
<tr>{header_html}</tr>
|
|
</thead>
|
|
<tbody>
|
|
{rows_html}
|
|
</tbody>
|
|
</table>
|
|
</body>
|
|
</html>
|
|
"""
|
|
|
|
return rendered
|
|
|
|
except csv.Error as e:
|
|
raise ValueError(f"Error parsing TSV: {e}")
|
|
except StopIteration:
|
|
return "<p>No data found in TSV input.</p>"
|
|
|
|
|
|
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()
|