Spaces:
Sleeping
Sleeping
File size: 1,849 Bytes
fb007f1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | # 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" |