Spaces:
Sleeping
Sleeping
| # utils/export.py (new file) | |
| import csv | |
| import json | |
| import base64 | |
| from io import BytesIO, StringIO | |
| def export_to_csv(explanation_data, filename="attributions.csv"): | |
| """Export explanation data to CSV""" | |
| output = StringIO() | |
| writer = csv.writer(output) | |
| if explanation_data and isinstance(explanation_data[0], dict): | |
| # SHAP/Captum format | |
| writer.writerow(['Token', 'Value', 'Position']) | |
| for item in explanation_data: | |
| writer.writerow([item.get('token', ''), item.get('value', 0), item.get('position', 0)]) | |
| else: | |
| # LIME format | |
| writer.writerow(['Feature', 'Weight']) | |
| for feature, weight in explanation_data: | |
| writer.writerow([feature, weight]) | |
| csv_string = output.getvalue() | |
| output.close() | |
| # Create downloadable link | |
| b64 = base64.b64encode(csv_string.encode()).decode() | |
| return f'<a href="data:file/csv;base64,{b64}" download="{filename}">Download CSV</a>' | |
| def export_to_json(explanation_data, filename="attributions.json"): | |
| """Export explanation data to JSON""" | |
| json_string = json.dumps(explanation_data, indent=2) | |
| b64 = base64.b64encode(json_string.encode()).decode() | |
| return f'<a href="data:application/json;base64,{b64}" download="{filename}">Download JSON</a>' | |
| def export_plot_as_png(plot_html, filename="attribution_plot.png"): | |
| """Extract PNG from plot HTML and create download link""" | |
| try: | |
| # Extract base64 data from HTML | |
| import re | |
| match = re.search(r'base64,([^"]+)', plot_html) | |
| if match: | |
| b64_data = match.group(1) | |
| return f'<a href="data:image/png;base64,{b64_data}" download="{filename}">Download PNG</a>' | |
| return "Download not available" | |
| except Exception as e: | |
| print(f"Export error: {e}") | |
| return "Download failed" |