IP-Safe / src /reporting /sheets_uploader.py
Yash
Claude Sonnet 4.6
Fix all 47 ruff lint errors to pass CI
74888a1
Raw History Blame Contribute Delete
21.5 kB
"""Google Sheets uploader for IP violation analysis results."""
import gspread
import httplib2
import google.auth.transport.requests
import google_auth_httplib2
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from typing import List, Dict, Optional
from loguru import logger
import os
import time
from datetime import datetime
import pickle
HEADER_FORMAT = {
"backgroundColor": {"red": 0.27, "green": 0.45, "blue": 0.77},
"textFormat": {"bold": True, "foregroundColor": {"red": 1, "green": 1, "blue": 1}},
"horizontalAlignment": "CENTER",
}
class GoogleSheetsUploader:
"""Upload analysis results to Google Sheets with embedded images."""
SCOPES = [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive.file",
]
def __init__(self, credentials_path: str = None, use_oauth: bool = False):
"""
Initialize Google Sheets uploader.
Args:
credentials_path: Path to service account JSON file (if use_oauth=False)
use_oauth: If True, use OAuth authentication instead of service account
"""
self.credentials_path = credentials_path
self.use_oauth = use_oauth
self.client = None
self.spreadsheet = None
self._sheets = {}
self._all_results_accumulated = []
self._authenticate()
def _authenticate(self):
"""Authenticate with Google Sheets API."""
try:
if self.use_oauth:
# Load OAuth token
token_path = "token.pickle"
if not os.path.exists(token_path):
raise FileNotFoundError(
"OAuth token not found! Please run authenticate_oauth.py first."
)
with open(token_path, "rb") as token:
creds = pickle.load(token)
# Refresh token if expired so Drive uploads don't fail mid-run
if creds.expired and creds.refresh_token:
logger.info("OAuth token expired, refreshing...")
creds.refresh(google.auth.transport.requests.Request())
with open(token_path, "wb") as token:
pickle.dump(creds, token)
logger.info("OAuth token refreshed and saved")
logger.info("Using OAuth authentication")
else:
# Use service account
creds = Credentials.from_service_account_file(
self.credentials_path, scopes=self.SCOPES
)
logger.info("Using service account authentication")
self.client = gspread.authorize(creds)
authorized_http = google_auth_httplib2.AuthorizedHttp(
creds, http=httplib2.Http(timeout=30)
)
self.drive_service = build("drive", "v3", http=authorized_http)
logger.info("Successfully authenticated with Google Sheets API")
except Exception as e:
logger.error(f"Failed to authenticate with Google Sheets: {e}")
raise
# ----------------------------------------------------------------
# Incremental API: initialize → append_batch (repeated) → finalize
# ----------------------------------------------------------------
def get_or_create_spreadsheet(self, title: str) -> tuple:
"""
Auto-create a new Google Sheet with the given title.
Makes it publicly viewable (anyone with link).
Returns:
(spreadsheet_id, spreadsheet_url)
"""
spreadsheet = self.client.create(title)
spreadsheet.share(None, perm_type="anyone", role="reader")
logger.success(f"Auto-created Google Sheet: {spreadsheet.url}")
return spreadsheet.id, spreadsheet.url
def initialize_sheets(self, spreadsheet_id: str) -> None:
"""
Initialize the spreadsheet for incremental insertion.
Creates all worksheets with headers. Must be called before append_batch().
Args:
spreadsheet_id: Google Sheets spreadsheet ID
"""
logger.info(f"Initializing Google Sheet: {spreadsheet_id}")
self.spreadsheet = self.client.open_by_key(spreadsheet_id)
# Store old worksheets to delete after creating new ones
# (Google Sheets requires at least 1 sheet to exist at all times)
old_worksheets = self.spreadsheet.worksheets()
logger.info(f"Found {len(old_worksheets)} existing sheets to replace")
# Create 3 client-focused worksheets with headers
self._sheets = {}
self._all_results_accumulated = []
# 1. Publishing Dashboard - Quick decision view (use temp name first)
sheet = self.spreadsheet.add_worksheet(
title="Publishing Dashboard (New)", rows=1000, cols=10
)
headers = [
"Image",
"Image ID",
"Status",
"Risk Level",
"Match Found",
"Rights Holder",
"Match Strength",
"AI Agreement",
"Action Required",
"Safe for Kids",
]
sheet.append_row(headers)
sheet.format("A1:J1", HEADER_FORMAT)
self._sheets["dashboard"] = sheet
# 2. Detailed Analysis - Deep dive with redesign suggestions (use temp name first)
sheet = self.spreadsheet.add_worksheet(
title="Detailed Analysis (New)", rows=1000, cols=12
)
headers = [
"Image",
"Image ID",
"Status",
"Risk Level",
"Match Found",
"Rights Holder",
"Match Strength",
"What Matches",
"Why It's Flagged",
"Suggested Changes",
"Model Details",
"Safe for Kids",
]
sheet.append_row(headers)
sheet.format("A1:L1", HEADER_FORMAT)
self._sheets["detailed"] = sheet
# 3. Summary Report (will be filled in finalize) (use temp name first)
sheet = self.spreadsheet.add_worksheet(
title="Summary Report (New)", rows=100, cols=4
)
headers = ["Metric", "Value"]
sheet.append_row(headers)
sheet.format("A1:B1", HEADER_FORMAT)
self._sheets["summary"] = sheet
# Now delete old worksheets (after creating new ones to avoid having 0 sheets)
logger.info(f"Deleting {len(old_worksheets)} old sheets...")
for worksheet in old_worksheets:
try:
self.spreadsheet.del_worksheet(worksheet)
except Exception as e:
logger.warning(f"Failed to delete old sheet {worksheet.title}: {e}")
# Rename new sheets to final names
logger.info("Renaming new sheets to final names...")
self._sheets["dashboard"].update_title("Publishing Dashboard")
self._sheets["detailed"].update_title("Detailed Analysis")
self._sheets["summary"].update_title("Summary Report")
logger.info("Initialized 3 client-focused worksheets with headers")
def upload_thumbnails_batch(
self, image_ids: List[str], thumbnail_map: Dict[str, str]
) -> Dict[str, str]:
"""
Upload thumbnails for a batch of image IDs to Google Drive.
Args:
image_ids: List of image IDs to upload thumbnails for
thumbnail_map: Full mapping of image_id to local thumbnail path
Returns:
Mapping of image_id to Google Drive thumbnail URL
"""
thumbnail_urls = {}
for image_id in image_ids:
thumbnail_path = thumbnail_map.get(image_id, "")
if thumbnail_path and os.path.exists(thumbnail_path):
last_error = None
for attempt in range(3):
try:
file_metadata = {"name": f"{image_id}_thumbnail.png"}
media = MediaFileUpload(thumbnail_path, mimetype="image/png")
file = (
self.drive_service.files()
.create(
body=file_metadata,
media_body=media,
fields="id, webContentLink",
)
.execute()
)
file_id = file.get("id")
self.drive_service.permissions().create(
fileId=file_id, body={"type": "anyone", "role": "reader"}
).execute()
image_url = (
f"https://drive.google.com/thumbnail?id={file_id}&sz=w200"
)
thumbnail_urls[image_id] = image_url
logger.debug(f"Uploaded thumbnail for {image_id}")
break
except Exception as e:
last_error = e
if attempt < 2:
wait = 2**attempt
logger.warning(
f"Thumbnail upload attempt {attempt + 1}/3 failed for {image_id}, retrying in {wait}s: {e}"
)
time.sleep(wait)
else:
logger.warning(
f"Failed to upload thumbnail {image_id} after 3 attempts: {last_error}"
)
thumbnail_urls[image_id] = "[Upload failed]"
else:
thumbnail_urls[image_id] = "[No thumbnail]"
return thumbnail_urls
def append_batch(
self, results_batch: List[Dict], thumbnail_urls: Dict[str, str]
) -> None:
"""
Append a batch of analysis results to 3 client-focused worksheets incrementally.
Args:
results_batch: List of result dicts (from orchestrator)
thumbnail_urls: Mapping of image_id to Google Drive thumbnail URLs (shown in Image column)
"""
self._all_results_accumulated.extend(results_batch)
dashboard_rows = []
detailed_rows = []
for result in results_batch:
if "error" in result and "consensus" not in result:
continue # Skip completely failed images
consensus = result.get("consensus", {})
image_meta = result.get("image_meta", {})
image_id = image_meta.get("image_id", "unknown")
# Format image ID nicely
formatted_id = (
image_id.replace("_", " ")
.replace("page", "Page")
.replace("img", "Image")
)
# Get thumbnail URL
thumbnail_url = thumbnail_urls.get(image_id, "[No image]")
# Kids safety cell value
kids_consensus = result.get("kids_consensus", {})
kids_safe = kids_consensus.get("safe_for_kids", "UNKNOWN")
if kids_safe == "YES":
kids_cell = "YES"
elif kids_safe == "NO":
kids_reason = (
kids_consensus.get("reason")
or "Flagged as unsafe for young children"
)
kids_cell = f"NO: {kids_reason}"
else:
kids_cell = "N/A (not analyzed)"
# Dashboard row - quick decision view
dashboard_rows.append(
[
thumbnail_url, # Image thumbnail link
formatted_id,
consensus.get("status", "⚠️ NEEDS REVIEW"),
consensus.get("risk_level", "Unknown"),
consensus.get("identified_ip", "None"),
consensus.get("ip_owner", "N/A"),
f"{consensus.get('avg_similarity', 0):.0f}% match",
consensus.get("ai_agreement_text", "Unknown"),
consensus.get("action_required", "Review required"),
kids_cell,
]
)
# Detailed Analysis row - with redesign suggestions
# Format "What Matches"
matching_elements = consensus.get("matching_elements", {})
what_matches = []
for category, details in matching_elements.items():
if isinstance(details, dict):
desc = details.get("description", "")
if desc and desc != "No match":
what_matches.append(f"• {category.title()}: {desc}")
what_matches_str = (
"\n".join(what_matches) if what_matches else "No specific elements"
)
# Format "Suggested Changes"
suggestions = consensus.get("redesign_suggestions", [])
suggested_changes = (
"\n".join([f"• {s}" for s in suggestions]) if suggestions else "N/A"
)
# Model details — dynamic across 1-3 models
model_results = result.get("model_results", [])
model_parts = [
f"{r.get('provider', r.get('model', 'Model'))}: {r.get('similarity_percentage', 0):.0f}%"
for r in model_results
if "similarity_percentage" in r
]
if model_parts:
model_details = (
" | ".join(model_parts)
+ f" | Avg: {consensus.get('avg_similarity', 0):.0f}%\nVariance: {consensus.get('similarity_stddev', 0):.1f}%"
)
else:
model_details = "No model data"
detailed_rows.append(
[
thumbnail_url, # Image thumbnail link
formatted_id,
consensus.get("status", "⚠️"),
consensus.get("risk_level", "Unknown"),
consensus.get("identified_ip", "None"),
consensus.get("ip_owner", "N/A"),
f"{consensus.get('avg_similarity', 0):.0f}% match",
what_matches_str,
consensus.get(
"combined_description", "No description"
), # FULL text
suggested_changes,
model_details,
kids_cell,
]
)
# Append to sheets
if dashboard_rows:
self._sheets["dashboard"].append_rows(dashboard_rows)
logger.info(f"Appended {len(dashboard_rows)} rows to Dashboard")
if detailed_rows:
self._sheets["detailed"].append_rows(detailed_rows)
logger.info(f"Appended {len(detailed_rows)} rows to Detailed Analysis")
def finalize_sheets(self) -> str:
"""
Write the final Summary Report sheet and return the spreadsheet URL.
Must be called after all append_batch() calls are complete.
Returns:
URL of the spreadsheet
"""
results = self._all_results_accumulated
total_images = len(results)
# Count status categories
status_counts = {}
risk_counts = {
"Minimal Risk": 0,
"Moderate Risk": 0,
"High Risk": 0,
"Critical Risk": 0,
}
ip_owner_risks = {}
kids_safe_count = 0
kids_unsafe_count = 0
kids_na_count = 0
for result in results:
# Kids safety tally
kids_consensus = result.get("kids_consensus", {})
kids_safe = kids_consensus.get("safe_for_kids", "UNKNOWN")
if kids_safe == "YES":
kids_safe_count += 1
elif kids_safe == "NO":
kids_unsafe_count += 1
else:
kids_na_count += 1
consensus = result.get("consensus", {})
# Status
status = consensus.get("status", "⚠️ NEEDS REVIEW")
status_counts[status] = status_counts.get(status, 0) + 1
# Risk
risk = consensus.get("risk_level", "Unknown")
if risk in risk_counts:
risk_counts[risk] += 1
# IP owners
ip_owner = consensus.get("ip_owner", "Unknown")
similarity = consensus.get("avg_similarity", 0)
if ip_owner not in ip_owner_risks:
ip_owner_risks[ip_owner] = {"count": 0, "max_risk": 0, "max_image": ""}
ip_owner_risks[ip_owner]["count"] += 1
if similarity > ip_owner_risks[ip_owner]["max_risk"]:
ip_owner_risks[ip_owner]["max_risk"] = similarity
ip_owner_risks[ip_owner]["max_image"] = result.get(
"image_meta", {}
).get("image_id", "unknown")
# Clear the existing summary sheet and write new data
summary_sheet = self._sheets["summary"]
summary_sheet.clear()
# Section A: Key Metrics
metrics_rows = [
["Metric", "Value"],
["Total Images Analyzed", total_images],
["Analysis Date", datetime.now().strftime("%Y-%m-%d")],
["Models Used", "GPT-5.2 + Gemini 3.1 Pro + Claude Opus 4.6"],
["", ""],
["PUBLISHING STATUS", ""],
["✅ Safe to Publish", status_counts.get("✅ SAFE TO PUBLISH", 0)],
["⚠️ Needs Review", status_counts.get("⚠️ NEEDS REVIEW", 0)],
["❌ Do Not Publish", status_counts.get("❌ DO NOT PUBLISH", 0)],
["", ""],
["RISK BREAKDOWN", ""],
["Minimal Risk (0-40%)", risk_counts["Minimal Risk"]],
["Moderate Risk (41-60%)", risk_counts["Moderate Risk"]],
["High Risk (61-80%)", risk_counts["High Risk"]],
["Critical Risk (81-100%)", risk_counts["Critical Risk"]],
["", ""],
["KIDS SAFETY (Ages 2-8)", ""],
["✅ Safe for Kids", kids_safe_count],
["❌ Not Safe for Kids", kids_unsafe_count],
]
if kids_na_count:
metrics_rows.append(["⚠️ Not Analyzed", kids_na_count])
metrics_rows += [["", ""]]
summary_sheet.append_rows(metrics_rows)
# Section B: IP Owners (add below metrics with spacing)
summary_sheet.append_rows([["", ""], ["DETECTED IP OWNERS", ""]])
ip_owner_rows = [
["Rights Holder", "Images Flagged", "Highest Risk Image", "Action Needed"]
]
for owner, data in sorted(
ip_owner_risks.items(), key=lambda x: x[1]["count"], reverse=True
):
ip_owner_rows.append(
[
owner,
data["count"],
f"{data['max_image']} ({data['max_risk']:.0f}%)",
"Legal review + redesign"
if data["max_risk"] > 60
else "Review required",
]
)
summary_sheet.append_rows(ip_owner_rows)
sheet_url = self.spreadsheet.url
logger.success(
f"Finalized Google Sheet with 3 client-focused sheets: {sheet_url}"
)
return sheet_url
# ----------------------------------------------------------------
# Backward-compatible monolithic API (used by upload_to_sheets.py)
# ----------------------------------------------------------------
def upload_report(
self,
results: List[Dict],
thumbnail_map: Dict[str, str],
spreadsheet_title: Optional[str] = None,
spreadsheet_id: Optional[str] = None,
) -> str:
"""
Upload analysis report to Google Sheets (backward-compatible).
For incremental upload, use initialize_sheets/append_batch/finalize_sheets.
Args:
results: List of analysis results
thumbnail_map: Mapping of image_id to thumbnail path
spreadsheet_title: Optional title for the spreadsheet
spreadsheet_id: Optional existing spreadsheet ID to use
Returns:
URL of the created Google Sheet
"""
try:
if spreadsheet_id:
self.initialize_sheets(spreadsheet_id)
else:
if spreadsheet_title is None:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
spreadsheet_title = f"IP Violation Analysis - {timestamp}"
logger.info(f"Creating Google Sheet: {spreadsheet_title}")
self.spreadsheet = self.client.create(spreadsheet_title)
self.initialize_sheets(self.spreadsheet.id)
# Upload all thumbnails at once
all_image_ids = [
r.get("image_meta", {}).get("image_id", "unknown") for r in results
]
thumbnail_urls = self.upload_thumbnails_batch(all_image_ids, thumbnail_map)
# Append all results as one batch
self.append_batch(results, thumbnail_urls)
# Finalize
return self.finalize_sheets()
except Exception as e:
logger.error(f"Failed to upload report to Google Sheets: {e}")
raise