AmaraCheryl commited on
Commit
6376b16
Β·
verified Β·
1 Parent(s): 4d7b17f

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +127 -0
main.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import requests
4
+ from fastapi import FastAPI, Request
5
+ from pydantic import BaseModel
6
+ from fastapi.middleware.cors import CORSMiddleware
7
+ from oauth import router as oauth_router
8
+ from audit import explain_risks
9
+
10
+ # ------------------------------------------------
11
+ # πŸ”§ Logging setup
12
+ # ------------------------------------------------
13
+ logging.basicConfig(
14
+ level=logging.INFO,
15
+ format="%(asctime)s [%(levelname)s] %(message)s",
16
+ )
17
+ logger = logging.getLogger(__name__)
18
+ logger.info("πŸš€ Starting Privacy Audit Backend (Hugging Face API)...")
19
+
20
+ # ------------------------------------------------
21
+ # βš™οΈ FastAPI app init
22
+ # ------------------------------------------------
23
+ app = FastAPI(title="Privacy Audit API", version="1.1.0")
24
+
25
+ # Allow frontend access (CORS)
26
+ app.add_middleware(
27
+ CORSMiddleware,
28
+ allow_origins=["*"],
29
+ allow_credentials=True,
30
+ allow_methods=["*"],
31
+ allow_headers=["*"],
32
+ )
33
+
34
+ # ------------------------------------------------
35
+ # πŸ” OAuth router
36
+ # ------------------------------------------------
37
+ try:
38
+ app.include_router(oauth_router)
39
+ logger.info("βœ… OAuth router loaded successfully.")
40
+ except Exception as e:
41
+ logger.exception(f"⚠️ Failed to include OAuth router: {e}")
42
+
43
+ # ------------------------------------------------
44
+ # πŸ€– Hugging Face API setup
45
+ # ------------------------------------------------
46
+ HF_API_URL = "https://api-inference.huggingface.co/models/google/flan-t5-small"
47
+ HF_TOKEN = os.getenv("HF_TOKEN") # Set in Hugging Face Space secrets
48
+ headers = {"Authorization": f"Bearer {HF_TOKEN}"}
49
+
50
+ def generate_plain_text(input_text: str):
51
+ """Call Hugging Face API instead of local model."""
52
+ logger.info(f"🧩 Generating explanation for input: {input_text[:60]}...")
53
+ try:
54
+ payload = {"inputs": f"Explain privacy risks in plain language:\n{input_text}"}
55
+ response = requests.post(HF_API_URL, headers=headers, json=payload, timeout=60)
56
+ if response.status_code == 200:
57
+ result = response.json()
58
+ if isinstance(result, list) and "generated_text" in result[0]:
59
+ explanation = result[0]["generated_text"]
60
+ else:
61
+ explanation = result[0].get("generated_text", str(result))
62
+ logger.info("βœ… Text generation complete.")
63
+ return explanation
64
+ else:
65
+ logger.error(f"❌ HF API Error: {response.status_code} {response.text}")
66
+ return f"Error: {response.text}"
67
+ except Exception as e:
68
+ logger.exception(f"❌ Error generating text: {e}")
69
+ return "Error: Could not generate explanation."
70
+
71
+ # ------------------------------------------------
72
+ # πŸ“€ Models
73
+ # ------------------------------------------------
74
+ class AuditInput(BaseModel):
75
+ findings: str
76
+
77
+ # ------------------------------------------------
78
+ # πŸ” Endpoints
79
+ # ------------------------------------------------
80
+ @app.get("/ping")
81
+ def ping():
82
+ return {"status": "ok", "message": "Backend is alive!"}
83
+
84
+ @app.post("/analyze")
85
+ def analyze(data: dict):
86
+ try:
87
+ os_apps = data.get("os_apps", [])
88
+ browser_exts = data.get("browser_extensions", [])
89
+ account_apps = data.get("account_apps", [])
90
+ explanation = explain_risks(os_apps, browser_exts, account_apps)
91
+ return {"plain_language": explanation}
92
+ except Exception as e:
93
+ logger.exception(f"❌ Error in /analyze: {e}")
94
+ return {"error": str(e)}
95
+
96
+ @app.get("/audit")
97
+ def audit_mvp():
98
+ findings = "App X has camera access, App Y has location access, Chrome has 5 extensions"
99
+ explanation = generate_plain_text(findings)
100
+ return {
101
+ "findings": findings,
102
+ "plain_language": explanation,
103
+ "risk_level": "Medium"
104
+ }
105
+
106
+ @app.post("/audit")
107
+ async def audit_mvp(data: dict):
108
+ try:
109
+ os_apps = data.get("os_apps", [])
110
+ browser_exts = data.get("browser_extensions", [])
111
+ account_apps = data.get("account_apps", [])
112
+
113
+ findings_text = (
114
+ f"Detected {len(os_apps)} installed apps, "
115
+ f"{len(browser_exts)} browser extensions, and "
116
+ f"{len(account_apps)} connected account apps."
117
+ )
118
+ explanation = generate_plain_text(findings_text)
119
+
120
+ return {
121
+ "findings": findings_text,
122
+ "plain_language": explanation,
123
+ "risk_level": "Medium"
124
+ }
125
+ except Exception as e:
126
+ logger.exception(f"❌ Error in /audit: {e}")
127
+ return {"error": str(e)}