First_agent_template / tools /dsa_transparency_report.py
Dave67350's picture
Create dsa_transparency_report.py
74bb918 verified
Raw
History Blame Contribute Delete
4.87 kB
# tools/dsa_transparency_report.py
from datetime import datetime
from fpdf import FPDF
import re
import gradio as gr
from langdetect import detect
# === PDF Export Function ===
def export_text_to_pdf(text, metadata=None, output_path=None, language="en"):
if output_path is None:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_path = f"dsa_transparency_report_{timestamp}.pdf"
pdf = FPDF()
pdf.add_page()
pdf.set_auto_page_break(auto=True, margin=15)
# Title
pdf.set_font("Arial", 'B', 16)
pdf.set_text_color(0, 51, 102)
pdf.cell(0, 15, "DSA Transparency Report", ln=True, align='C')
pdf.ln(8)
# Metadata
if metadata:
pdf.set_font("Arial", '', 12)
pdf.set_text_color(90, 90, 90)
pdf.multi_cell(0, 10, f"Organization: {metadata.get('organization', 'N/A')}")
pdf.multi_cell(0, 10, f"Completed by: {metadata.get('completed_by', 'N/A')} ({metadata.get('role', 'N/A')})")
pdf.multi_cell(0, 10, f"Timestamp: {metadata.get('timestamp', 'N/A')}")
pdf.ln(5)
# Body
pdf.set_font("Arial", '', 12)
pdf.set_text_color(0, 0, 0)
for line in text.strip().split('\n'):
if line.startswith("## "):
section = line.replace("## ", "").strip()
pdf.set_font("Arial", 'B', 13)
pdf.set_text_color(30, 30, 120)
pdf.ln(6)
pdf.cell(0, 10, section, ln=True)
pdf.set_font("Arial", '', 12)
pdf.set_text_color(0, 0, 0)
elif line.startswith("- **"):
match = re.match(r"- \*\*(.+?)\*\*: (.+)", line)
if match:
label, value = match.groups()
pdf.set_font("Arial", 'B', 12)
pdf.cell(0, 10, f"{label}:", ln=True)
pdf.set_font("Arial", '', 12)
pdf.multi_cell(0, 10, value)
else:
pdf.multi_cell(0, 10, line)
pdf.output(output_path)
return output_path
# === Questions ===
QUESTIONS = [
("organization", "What is the name of your organization?"),
("completed_by", "Who is completing this report?"),
("role", "What is your role?"),
("reporting_period", "What is the reporting period (e.g. Q1 2025)?"),
("platform", "Which platform/service does this report apply to?"),
("moderation_volume", "How many content moderation actions occurred?"),
("appeals_count", "How many appeals were received?"),
("automated_tools", "What automated tools are used for moderation?"),
("government_requests", "How many content removal requests were from authorities?"),
("transparency_measures", "What transparency measures were implemented?")
]
def get_questions():
return QUESTIONS
# === Tool Execution ===
def run_tool():
state = {"step": 0, "answers": {}}
def step_by_step_agent(user_input, state):
step = state["step"]
answers = state["answers"]
if step > 0:
key, _ = QUESTIONS[step - 1]
answers[key] = user_input
if step < len(QUESTIONS):
next_q = QUESTIONS[step][1]
state["step"] += 1
return next_q, state, None
content = "\n".join([f"- **{label}**: {answers.get(key, '')}" for key, label in QUESTIONS])
try:
lang = detect(content) if len(content.strip()) > 3 else "en"
except:
lang = "en"
metadata = {
"organization": answers.get("organization"),
"completed_by": answers.get("completed_by"),
"role": answers.get("role"),
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
pdf_path = export_text_to_pdf(content, metadata=metadata, language=lang)
return "✅ Transparency report completed. Download below.", {"done": True}, pdf_path
with gr.Blocks(title="DSA Transparency Report Tool") as demo:
chatbot = gr.Chatbot(label="📊 Transparency Assistant", value=[{"role": "assistant", "content": QUESTIONS[0][1]}], type="messages")
msg = gr.Textbox(label="Your answer")
state_var = gr.State(state)
file_output = gr.File(label="Download PDF")
reset_btn = gr.Button("🔁 Restart")
def chat_logic(msg_in, state_in):
reply, updated_state, file = step_by_step_agent(msg_in, state_in)
messages = [{"role": "user", "content": msg_in}]
if reply:
messages.append({"role": "assistant", "content": reply})
return messages, updated_state, file
def reset():
return [{"role": "assistant", "content": QUESTIONS[0][1]}], {"step": 0, "answers": {}}, None
msg.submit(chat_logic, [msg, state_var], [chatbot, state_var, file_output])
reset_btn.click(reset, outputs=[chatbot, state_var, file_output])
demo.launch(show_api=False)