atharvaballa's picture
fixed ui
a07ace5
Raw
History Blame Contribute Delete
3.68 kB
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from datetime import datetime
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image
from reportlab.lib.styles import getSampleStyleSheet
from datetime import datetime
import os
from PIL import Image as PILImage
def generate_report(label, confidence, image, heatmap):
try:
if not label or image is None:
return None
# =========================
# CREATE REPORTS DIRECTORY
# =========================
reports_dir = "reports"
os.makedirs(reports_dir, exist_ok=True) # auto-create if not exists
# =========================
# FILE PATH INSIDE FOLDER
# =========================
file_name = f"Deepfake_Detection_Report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
file_path = os.path.join(reports_dir, file_name)
doc = SimpleDocTemplate(file_path)
styles = getSampleStyleSheet()
content = []
# TITLE
content.append(Paragraph("Deepfake Detection Report", styles['Title']))
content.append(Spacer(1, 12))
# TIMESTAMP
content.append(Paragraph(
f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
styles['Normal']
))
content.append(Spacer(1, 12))
# RESULTS
content.append(Paragraph(f"<b>Prediction:</b> {label}", styles['Normal']))
content.append(Spacer(1, 10))
content.append(Paragraph(f"<b>Confidence:</b> {confidence}", styles['Normal']))
content.append(Spacer(1, 15))
# =========================
# TEMP FILES (KEEP ROOT CLEAN)
# =========================
temp_dir = "temp"
os.makedirs(temp_dir, exist_ok=True)
image_path = os.path.join(temp_dir, "input.png")
heatmap_path = os.path.join(temp_dir, "heatmap.png")
# SAVE INPUT IMAGE
if isinstance(image, PILImage.Image):
image.save(image_path)
if os.path.exists(image_path):
content.append(Paragraph("<b>Input Image:</b>", styles['Normal']))
content.append(Spacer(1, 10))
content.append(Image(image_path, width=300, height=200))
content.append(Spacer(1, 15))
# HANDLE HEATMAP
if heatmap is not None:
try:
if isinstance(heatmap, PILImage.Image):
heatmap.save(heatmap_path)
else:
heatmap = PILImage.fromarray(heatmap)
heatmap.save(heatmap_path)
if os.path.exists(heatmap_path):
content.append(Paragraph("<b>Explainability Heatmap:</b>", styles['Normal']))
content.append(Spacer(1, 10))
content.append(Image(heatmap_path, width=300, height=200))
content.append(Spacer(1, 15))
except Exception as e:
print("Heatmap error:", e)
# INTERPRETATION
interpretation = (
"The uploaded image is likely AI-generated (deepfake)."
if label == "Fake"
else "The uploaded image is likely authentic."
)
content.append(Paragraph(f"<b>Interpretation:</b> {interpretation}", styles['Normal']))
# BUILD PDF
doc.build(content)
# CLEANUP TEMP FILES
for f in [image_path, heatmap_path]:
if os.path.exists(f):
os.remove(f)
return file_path
except Exception as e:
print("REPORT ERROR:", e)
return None