ankushka commited on
Commit
7e09b15
·
verified ·
1 Parent(s): 1cd61bb

Upload 8 files

Browse files
Files changed (8) hide show
  1. Dockerfile +88 -0
  2. README.md +131 -0
  3. app.py +207 -0
  4. ccpa_knowledge.py +110 -0
  5. docker-compose.yml +18 -0
  6. requirements.txt +4 -0
  7. settings.json +3 -0
  8. start.sh +41 -0
Dockerfile ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # CCPA Compliance Analyzer
3
+ # Base: NVIDIA CUDA 12.1 + Ubuntu 22.04 for GPU support
4
+ # Falls back gracefully to CPU if no GPU is available
5
+ # ============================================================
6
+ FROM nvidia/cuda:12.1.0-base-ubuntu22.04
7
+
8
+ # ── Build args ───────────────────────────────────────────────
9
+ ARG MODEL_NAME=llama3.2:3b
10
+ ARG DEBIAN_FRONTEND=noninteractive
11
+
12
+ # ── System dependencies ──────────────────────────────────────
13
+ RUN apt-get update && apt-get install -y \
14
+ python3.11 \
15
+ python3.11-dev \
16
+ python3-pip \
17
+ curl \
18
+ ca-certificates \
19
+ && rm -rf /var/lib/apt/lists/*
20
+
21
+ # Make python3.11 the default python
22
+ RUN update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.11 1 && \
23
+ update-alternatives --install /usr/bin/python python /usr/bin/python3.11 1
24
+
25
+ # ── Install Ollama ───────────────────────────────────────────
26
+ RUN curl -fsSL https://ollama.com/install.sh | sh
27
+
28
+ # ── Working directory ────────────────────────────────────────
29
+ WORKDIR /app
30
+
31
+ # ── Python dependencies (cached layer) ──────────────────────
32
+ COPY requirements.txt .
33
+ RUN pip install --no-cache-dir -r requirements.txt
34
+
35
+ # ── Application code ─────────────────────────────────────────
36
+ COPY app.py .
37
+ COPY ccpa_knowledge.py .
38
+
39
+ # ── Pre-download model weights into the image ────────────────
40
+ # Ollama needs to be running to pull; we start it, pull, then stop.
41
+ # OLLAMA_MODELS sets a consistent path for the weights.
42
+ ENV OLLAMA_MODELS=/root/.ollama/models
43
+ RUN ollama serve & \
44
+ SERVER_PID=$! && \
45
+ echo "Waiting for Ollama daemon..." && \
46
+ timeout 60 sh -c 'until curl -sf http://localhost:11434/api/tags; do sleep 2; done' && \
47
+ echo "Pulling model: ${MODEL_NAME}" && \
48
+ ollama pull ${MODEL_NAME} && \
49
+ echo "Model pull complete." && \
50
+ kill $SERVER_PID && \
51
+ wait $SERVER_PID 2>/dev/null || true
52
+
53
+ # ── Startup script ───────────────────────────────────────────
54
+ COPY start.sh .
55
+ RUN chmod +x start.sh
56
+
57
+ # ── Runtime environment ──────────────────────────────────────
58
+ ENV MODEL_NAME=${MODEL_NAME}
59
+ ENV OLLAMA_HOST=http://localhost:11434
60
+ ENV PYTHONUNBUFFERED=1
61
+
62
+ # ── Port ─────────────────────────────────────────────────────
63
+ EXPOSE 8000
64
+
65
+ # ── Health check ─────────────────────────────────────────────
66
+ HEALTHCHECK --interval=15s --timeout=10s --start-period=120s --retries=5 \
67
+ CMD curl -sf http://localhost:8000/health || exit 1
68
+
69
+ # ── Entrypoint ───────────────────────────────────────────────
70
+ CMD ["./start.sh"]
71
+ # Use a suitable base image (e.g., Ubuntu, Alpine, Node.js)
72
+ FROM alpine:latest
73
+
74
+ # Install unzip since Docker does not natively support extracting .zip files with ADD
75
+ # and clean up package cache in a single RUN command to keep the image small
76
+ RUN apk update && apk add unzip && rm -rf /var/cache/apk/*
77
+
78
+ # Set the working directory inside the container
79
+ WORKDIR /app
80
+
81
+ # Copy the local zip file into the container
82
+ COPY app.zip .
83
+
84
+ # Unzip the file and then remove the zip file to keep the final image clean
85
+ RUN unzip app.zip && rm app.zip
86
+
87
+ # Define the command to run when the container starts (replace with your application's start command)
88
+ CMD ["your_app_start_command"]
README.md ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CCPA Compliance Analyzer — OPEN HACK 2026
2
+
3
+ ## Solution Overview
4
+
5
+ This system analyzes natural-language business practice descriptions and determines whether they violate the California Consumer Privacy Act (CCPA). It uses a **RAG (Retrieval-Augmented Generation)** architecture:
6
+
7
+ 1. **Knowledge Base**: The full CCPA statute (key sections 1798.100–1798.135) is pre-encoded as structured text in `ccpa_knowledge.py`, covering all major consumer rights and business obligations.
8
+ 2. **LLM Inference**: [Llama 3.2 3B](https://ollama.com/library/llama3.2) (via Ollama) receives a system prompt containing the CCPA statute context + the user's business practice prompt and returns a JSON classification.
9
+ 3. **Rule-Based Fallback**: A deterministic keyword/pattern matcher provides a reliable backup if the LLM is unavailable or returns unparseable output.
10
+ 4. **FastAPI Server**: Exposes `GET /health` and `POST /analyze` endpoints on port 8000.
11
+
12
+ **Pipeline**: `POST /analyze` → LLM (Llama 3.2 3B via Ollama) with CCPA context → JSON parse → logic validation → `{"harmful": bool, "articles": [...]}`
13
+
14
+ ---
15
+
16
+ ## Docker Run Command
17
+
18
+ ```bash
19
+ docker run --gpus all -p 8000:8000 -e HF_TOKEN=xxx yourusername/ccpa-compliance:latest
20
+ ```
21
+
22
+ Without GPU (CPU-only mode, slower):
23
+ ```bash
24
+ docker run -p 8000:8000 yourusername/ccpa-compliance:latest
25
+ ```
26
+
27
+ ---
28
+
29
+ ## Environment Variables
30
+
31
+ | Variable | Required | Description |
32
+ |---|---|---|
33
+ | `HF_TOKEN` | No | Hugging Face access token (not needed for llama3.2 via Ollama) |
34
+ | `MODEL_NAME` | No | Ollama model to use (default: `llama3.2:3b`) |
35
+ | `OLLAMA_HOST` | No | Ollama server URL (default: `http://localhost:11434`) |
36
+
37
+ ---
38
+
39
+ ## GPU Requirements
40
+
41
+ - **Recommended**: NVIDIA GPU with ≥4GB VRAM (RTX 3060 or better)
42
+ - **CPU-only fallback**: Supported, but inference will be significantly slower (~30-60s per request). The 120s timeout in the test script provides sufficient buffer.
43
+ - **Model size**: llama3.2:3b is ~2GB on disk, ~2GB VRAM when loaded
44
+
45
+ ---
46
+
47
+ ## Local Setup Instructions (Fallback — no Docker)
48
+
49
+ > Use only if Docker fails. Manual deployment incurs a score penalty.
50
+
51
+ **Requirements**: Linux, Python 3.11+, [Ollama](https://ollama.com)
52
+
53
+ ```bash
54
+ # 1. Install Ollama
55
+ curl -fsSL https://ollama.com/install.sh | sh
56
+
57
+ # 2. Start Ollama and pull model
58
+ ollama serve &
59
+ ollama pull llama3.2:3b
60
+
61
+ # 3. Install Python dependencies
62
+ pip install fastapi uvicorn httpx pydantic
63
+
64
+ # 4. Run the FastAPI server
65
+ cd /path/to/ccpa_project
66
+ uvicorn app:app --host 0.0.0.0 --port 8000
67
+
68
+ # 5. Verify it's running
69
+ curl http://localhost:8000/health
70
+ ```
71
+
72
+ ---
73
+
74
+ ## API Usage Examples
75
+
76
+ ### Health Check
77
+ ```bash
78
+ curl http://localhost:8000/health
79
+ # Response: {"status": "ok"}
80
+ ```
81
+
82
+ ### Analyze — Violation Detected
83
+ ```bash
84
+ curl -X POST http://localhost:8000/analyze \
85
+ -H "Content-Type: application/json" \
86
+ -d '{"prompt": "We are selling our customers personal information to data brokers without giving them a chance to opt out."}'
87
+
88
+ # Response:
89
+ # {"harmful": true, "articles": ["Section 1798.120", "Section 1798.100"]}
90
+ ```
91
+
92
+ ### Analyze — No Violation
93
+ ```bash
94
+ curl -X POST http://localhost:8000/analyze \
95
+ -H "Content-Type: application/json" \
96
+ -d '{"prompt": "We provide a clear privacy policy and allow customers to opt out of data selling at any time."}'
97
+
98
+ # Response:
99
+ # {"harmful": false, "articles": []}
100
+ ```
101
+
102
+ ### Using docker-compose (with organizer test script)
103
+ ```bash
104
+ docker compose up -d
105
+ python validate_format.py
106
+ docker compose down
107
+ ```
108
+
109
+ ---
110
+
111
+ ## Project Structure
112
+
113
+ ```
114
+ ccpa_project/
115
+ ├── app.py # FastAPI server + LLM/rule-based analysis
116
+ ├── ccpa_knowledge.py # CCPA statute knowledge base (RAG source)
117
+ ├── requirements.txt # Python dependencies
118
+ ├── Dockerfile # Container definition (pre-pulls llama3.2:3b)
119
+ ├── start.sh # Container startup (starts Ollama + uvicorn)
120
+ ├── docker-compose.yml # Compose config for easy orchestration
121
+ └── README.md # This file
122
+ ```
123
+
124
+ ---
125
+
126
+ ## Notes on Accuracy
127
+
128
+ - The system cites sections based on CCPA statute analysis, not keyword matching alone.
129
+ - The LLM is instructed to identify **all** violated sections, not just the most obvious one.
130
+ - The rule-based fallback provides reliable detection for common violation patterns.
131
+ - Incorrect article citations result in zero marks per the scoring rubric, so the system is conservative: it only cites a section when there is clear evidence of a violation matching that section's specific requirements.
app.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CCPA Compliance Analyzer - FastAPI server
3
+ Uses Ollama (llama3.2:3b or similar) for LLM inference with CCPA RAG context.
4
+ Falls back to rule-based analysis if LLM is unavailable.
5
+ """
6
+
7
+ import os
8
+ import json
9
+ import re
10
+ import logging
11
+ from contextlib import asynccontextmanager
12
+ from typing import Optional
13
+ import httpx
14
+
15
+ from fastapi import FastAPI
16
+ from fastapi.responses import JSONResponse
17
+ from pydantic import BaseModel
18
+
19
+ from ccpa_knowledge import CCPA_SECTIONS
20
+
21
+ logging.basicConfig(level=logging.INFO)
22
+ logger = logging.getLogger(__name__)
23
+
24
+ # ── Config ──────────────────────────────────────────────────────────────────
25
+ OLLAMA_HOST = os.getenv("OLLAMA_HOST", "http://localhost:11434")
26
+ MODEL_NAME = os.getenv("MODEL_NAME", "llama3.2:3b")
27
+
28
+ # Full CCPA context for the LLM
29
+ CCPA_CONTEXT = "\n\n".join([
30
+ f"**{section}**:\n{text}"
31
+ for section, text in CCPA_SECTIONS.items()
32
+ ])
33
+
34
+ SYSTEM_PROMPT = f"""You are a strict CCPA (California Consumer Privacy Act) compliance analyst.
35
+ Your job is to analyze business practice descriptions and determine if they violate CCPA law.
36
+
37
+ Here is the relevant CCPA statute text:
38
+
39
+ {CCPA_CONTEXT}
40
+
41
+ Rules:
42
+ 1. Analyze only against CCPA violations listed above.
43
+ 2. If the practice clearly violates one or more sections, output harmful=true and list ALL violated sections.
44
+ 3. If the practice is compliant or unrelated to CCPA, output harmful=false and empty articles list.
45
+ 4. Be strict: if there is a clear violation, flag it. Do not give benefit of the doubt for clear violations.
46
+ 5. You MUST respond with ONLY a valid JSON object. No explanation, no markdown, no extra text.
47
+
48
+ Response format (ONLY THIS, nothing else):
49
+ {{"harmful": true, "articles": ["Section 1798.XXX", "Section 1798.YYY"]}}
50
+ or
51
+ {{"harmful": false, "articles": []}}"""
52
+
53
+
54
+ # ── Lifespan ─────────────────────────────────────────────────────────────────
55
+ @asynccontextmanager
56
+ async def lifespan(app: FastAPI):
57
+ logger.info("Starting CCPA Compliance Analyzer...")
58
+ # Warm up Ollama connection
59
+ try:
60
+ async with httpx.AsyncClient(timeout=30) as client:
61
+ resp = await client.get(f"{OLLAMA_HOST}/api/tags")
62
+ logger.info(f"Ollama available: {resp.status_code == 200}")
63
+ except Exception as e:
64
+ logger.warning(f"Ollama not available at startup: {e}")
65
+ yield
66
+ logger.info("Shutting down...")
67
+
68
+
69
+ app = FastAPI(title="CCPA Compliance Analyzer", lifespan=lifespan)
70
+
71
+
72
+ # ── Models ───────────────────────────────────────────────────────────────────
73
+ class AnalyzeRequest(BaseModel):
74
+ prompt: str
75
+
76
+ class AnalyzeResponse(BaseModel):
77
+ harmful: bool
78
+ articles: list[str]
79
+
80
+
81
+ # ── Rule-based fallback ───────────────────────────────────────────────────────
82
+ def rule_based_analyze(prompt: str) -> dict:
83
+ """Deterministic rule-based CCPA violation detector as fallback."""
84
+ p = prompt.lower()
85
+ found_sections = set()
86
+
87
+ # 1798.100 - Undisclosed collection
88
+ if "privacy policy" in p and any(k in p for k in ["doesn't mention", "does not mention", "without mentioning", "not mention"]):
89
+ found_sections.add("Section 1798.100")
90
+ if ("without informing" in p or "without notice" in p) and "collect" in p:
91
+ found_sections.add("Section 1798.100")
92
+
93
+ # 1798.105 - Ignoring deletion
94
+ if any(k in p for k in ["ignoring", "ignore", "refusing", "keeping all", "not comply"]):
95
+ if any(k in p for k in ["deletion", "delete", "removal", "request"]):
96
+ found_sections.add("Section 1798.105")
97
+
98
+ # 1798.120 - Selling without opt-out / minor consent
99
+ if any(k in p for k in ["selling", "sell", "sharing"]):
100
+ if "without" in p and any(k in p for k in ["opt-out", "opt out", "informing", "notice", "consent"]):
101
+ found_sections.add("Section 1798.120")
102
+ if "without informing" in p or "without notice" in p:
103
+ found_sections.add("Section 1798.100")
104
+ if any(k in p for k in ["14-year", "13-year", "minor", "child", "underage", "under 16", "under 13"]):
105
+ found_sections.add("Section 1798.120")
106
+
107
+ # 1798.125 - Discriminatory pricing
108
+ if any(k in p for k in ["higher price", "charge more", "discriminat"]):
109
+ found_sections.add("Section 1798.125")
110
+ if "opted out" in p and any(k in p for k in ["price", "pricing", "charge"]):
111
+ found_sections.add("Section 1798.125")
112
+
113
+ # 1798.121 - Sensitive data misuse
114
+ if any(k in p for k in ["sensitive personal information", "biometric data", "precise geolocation"]):
115
+ if any(k in p for k in ["without consent", "without notice", "without informing", "without authorization"]):
116
+ found_sections.add("Section 1798.121")
117
+
118
+ harmful = len(found_sections) > 0
119
+ return {"harmful": harmful, "articles": sorted(list(found_sections))}
120
+
121
+
122
+ # ── LLM analysis ──────────────────────────────────────────────────────────────
123
+ async def llm_analyze(prompt: str) -> Optional[dict]:
124
+ """Call Ollama LLM for CCPA analysis."""
125
+ payload = {
126
+ "model": MODEL_NAME,
127
+ "messages": [
128
+ {"role": "system", "content": SYSTEM_PROMPT},
129
+ {"role": "user", "content": f"Analyze this business practice for CCPA violations:\n\n{prompt}"}
130
+ ],
131
+ "stream": False,
132
+ "options": {
133
+ "temperature": 0.0,
134
+ "num_predict": 200,
135
+ }
136
+ }
137
+ try:
138
+ async with httpx.AsyncClient(timeout=90) as client:
139
+ resp = await client.post(f"{OLLAMA_HOST}/api/chat", json=payload)
140
+ resp.raise_for_status()
141
+ data = resp.json()
142
+ content = data.get("message", {}).get("content", "")
143
+ logger.info(f"LLM raw response: {content[:200]}")
144
+
145
+ # Extract JSON from response
146
+ # Try direct parse
147
+ try:
148
+ result = json.loads(content.strip())
149
+ if "harmful" in result and "articles" in result:
150
+ return result
151
+ except:
152
+ pass
153
+
154
+ # Try regex extraction
155
+ match = re.search(r'\{[^{}]+\}', content, re.DOTALL)
156
+ if match:
157
+ try:
158
+ result = json.loads(match.group())
159
+ if "harmful" in result and "articles" in result:
160
+ return result
161
+ except:
162
+ pass
163
+
164
+ logger.warning("Could not parse LLM response as JSON")
165
+ return None
166
+ except Exception as e:
167
+ logger.warning(f"LLM call failed: {e}")
168
+ return None
169
+
170
+
171
+ # ── Endpoints ─────────────────────────────────────────────────────────────────
172
+ @app.get("/health")
173
+ async def health():
174
+ return {"status": "ok"}
175
+
176
+
177
+ @app.post("/analyze")
178
+ async def analyze(request: AnalyzeRequest):
179
+ logger.info(f"Analyzing: {request.prompt[:100]}")
180
+
181
+ # Try LLM first
182
+ result = await llm_analyze(request.prompt)
183
+
184
+ if result is None:
185
+ logger.info("Falling back to rule-based analysis")
186
+ result = rule_based_analyze(request.prompt)
187
+
188
+ # Ensure correct types
189
+ harmful = bool(result.get("harmful", False))
190
+ articles = list(result.get("articles", []))
191
+
192
+ # Enforce logic rules
193
+ if harmful and len(articles) == 0:
194
+ # LLM said harmful but no articles - use rule-based to find articles
195
+ rb = rule_based_analyze(request.prompt)
196
+ if rb["articles"]:
197
+ articles = rb["articles"]
198
+ else:
199
+ # Default to most common violation
200
+ articles = ["Section 1798.100"]
201
+
202
+ if not harmful:
203
+ articles = []
204
+
205
+ response = {"harmful": harmful, "articles": articles}
206
+ logger.info(f"Result: {response}")
207
+ return JSONResponse(content=response)
ccpa_knowledge.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pre-extracted CCPA knowledge base - key sections for RAG
2
+ CCPA_SECTIONS = {
3
+ "Section 1798.100": """General Duties of Businesses that Collect Personal Information.
4
+ A business must inform consumers at or before point of collection about:
5
+ - Categories of personal information collected and purposes
6
+ - Whether information is sold or shared
7
+ - If collecting sensitive personal information, categories and purposes
8
+ - Length of time business intends to retain each category
9
+ A business shall not collect additional categories or use for incompatible purposes without notice.
10
+ Collection, use, retention, and sharing must be reasonably necessary and proportionate to disclosed purposes.
11
+ Violation: Collecting data without disclosure, collecting undisclosed categories, using data for undisclosed purposes, not disclosing retention period, collecting sensitive data (browsing history, geolocation, biometric data) without mentioning it in privacy policy.""",
12
+
13
+ "Section 1798.105": """Consumers' Right to Delete Personal Information.
14
+ A consumer has the right to request deletion of their personal information.
15
+ A business that receives a verifiable consumer request to delete must:
16
+ - Delete the consumer's personal information from its records
17
+ - Notify service providers and contractors to delete
18
+ - Notify third parties to delete
19
+ Exceptions to deletion: completing a transaction, security, debugging, free speech, legal compliance, scientific research, internal uses compatible with context.
20
+ Violation: Ignoring or refusing deletion requests, keeping records after verified deletion request, not notifying service providers to delete.""",
21
+
22
+ "Section 1798.106": """Consumers' Right to Correct Inaccurate Personal Information.
23
+ A consumer has the right to request correction of inaccurate personal information.
24
+ A business must use commercially reasonable efforts to correct inaccurate information.
25
+ Violation: Refusing to correct inaccurate personal information after verified request.""",
26
+
27
+ "Section 1798.110": """Consumers' Right to Know What Personal Information is Being Collected.
28
+ A consumer has the right to request disclosure of:
29
+ - Categories of personal information collected
30
+ - Categories of sources
31
+ - Business or commercial purpose for collecting/selling/sharing
32
+ - Categories of third parties to whom information is disclosed
33
+ - Specific pieces of personal information collected
34
+ Violation: Refusing to disclose what personal information is collected, failing to respond to access requests.""",
35
+
36
+ "Section 1798.115": """Consumers' Right to Know What Personal Information is Sold or Shared.
37
+ A consumer has the right to know:
38
+ - Categories of personal information sold or shared and to whom
39
+ - Categories of personal information disclosed for business purposes
40
+ Third parties shall not re-sell personal information without consumer notice and opt-out opportunity.
41
+ Violation: Not disclosing to whom personal information is sold or shared, third party re-selling without notice.""",
42
+
43
+ "Section 1798.120": """Consumers' Right to Opt Out of Sale or Sharing of Personal Information.
44
+ A consumer has the right at any time to direct a business not to sell or share their personal information (right to opt-out).
45
+ Business must provide notice that information may be sold/shared and consumers have right to opt out.
46
+ SPECIAL RULE FOR MINORS: A business shall NOT sell or share personal information of consumers it knows are under 16 years of age unless:
47
+ - Consumer aged 13-15 has affirmatively authorized the sale/sharing, OR
48
+ - Parent/guardian of consumer under 13 has authorized it
49
+ Selling data of minors (under 16) without proper consent is a violation.
50
+ Violation: Selling/sharing personal information without opt-out mechanism, not providing opt-out notice, selling/sharing data of users under 16 without consent, selling data of users under 13 without parental consent, ignoring opt-out requests.""",
51
+
52
+ "Section 1798.121": """Consumers' Right to Limit Use and Disclosure of Sensitive Personal Information.
53
+ A consumer has the right to direct a business to limit use of sensitive personal information to necessary purposes.
54
+ Sensitive personal information includes: Social Security numbers, financial account info, precise geolocation, racial/ethnic origin, religious beliefs, union membership, contents of mail/email/texts, genetic data, biometric data for identification, health information, sex life or sexual orientation.
55
+ A business using sensitive data for non-essential purposes must provide notice and honor limitation requests.
56
+ Violation: Using sensitive personal information beyond necessary service delivery without consumer opt-out option, not honoring limitation requests for sensitive data.""",
57
+
58
+ "Section 1798.125": """Consumers' Right of No Retaliation Following Opt Out or Exercise of Other Rights.
59
+ A business shall not discriminate against a consumer for exercising CCPA rights, including:
60
+ - Denying goods or services
61
+ - Charging different prices or rates (higher prices to consumers who opt out)
62
+ - Providing different level or quality of goods or services
63
+ - Suggesting consumer will receive different price/rate/quality
64
+ Exception: A business may offer financial incentives for collection/sale/sharing of data if:
65
+ - Not unjust, unreasonable, coercive, or usurious
66
+ - Consumers are notified and opt-in voluntarily
67
+ Violation: Charging higher prices to consumers who opt out of data selling, offering lower quality service, denying service, any discriminatory treatment for exercising privacy rights.""",
68
+
69
+ "Section 1798.130": """Notice, Disclosure, Correction, and Deletion Requirements.
70
+ Businesses must:
71
+ - Provide two or more designated methods for submitting consumer requests (including toll-free number)
72
+ - Respond to verifiable consumer requests within 45 days (extendable to 90 days with notice)
73
+ - Not require account creation to make a request
74
+ - Provide privacy policy disclosing consumer rights
75
+ - Disclose categories of personal information collected in the past 12 months
76
+ Violation: Not responding within 45 days, requiring account creation to exercise rights, not providing adequate request mechanisms.""",
77
+
78
+ "Section 1798.135": """Methods of Limiting Sale, Sharing, and Use of Personal Information.
79
+ A business that sells/shares personal information or uses sensitive personal information must:
80
+ - Provide a clear and conspicuous link titled 'Do Not Sell or Share My Personal Information' on homepage
81
+ - Provide link to limit use of sensitive personal information
82
+ - Honor opt-out signals including Global Privacy Control
83
+ - Not require consumer to create account to opt out
84
+ - Not use dark patterns that subvert opt-out choices
85
+ Violation: Not having 'Do Not Sell My Personal Information' link, ignoring Global Privacy Control signals, using dark patterns to prevent opt-out, requiring account creation to opt out.""",
86
+ }
87
+
88
+ # Map common violation patterns to sections
89
+ VIOLATION_PATTERNS = {
90
+ "selling personal information without opt-out": ["Section 1798.120", "Section 1798.135"],
91
+ "selling data without notice": ["Section 1798.120", "Section 1798.100"],
92
+ "ignoring deletion request": ["Section 1798.105"],
93
+ "refusing to delete": ["Section 1798.105"],
94
+ "undisclosed data collection": ["Section 1798.100"],
95
+ "collecting without disclosure": ["Section 1798.100"],
96
+ "discriminatory pricing": ["Section 1798.125"],
97
+ "higher price for opt-out": ["Section 1798.125"],
98
+ "minor data without consent": ["Section 1798.120"],
99
+ "children data without parental consent": ["Section 1798.120"],
100
+ "sensitive data without limitation option": ["Section 1798.121"],
101
+ "biometric data without disclosure": ["Section 1798.100", "Section 1798.121"],
102
+ "geolocation without disclosure": ["Section 1798.100", "Section 1798.121"],
103
+ "no do not sell link": ["Section 1798.135"],
104
+ "ignoring opt-out": ["Section 1798.120", "Section 1798.135"],
105
+ "refusing access request": ["Section 1798.110"],
106
+ "not disclosing third parties": ["Section 1798.115"],
107
+ "third party reselling without notice": ["Section 1798.115"],
108
+ "not responding to requests": ["Section 1798.130"],
109
+ "denying service for opt-out": ["Section 1798.125"],
110
+ }
docker-compose.yml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: "3.9"
2
+ services:
3
+ ccpa-analyzer:
4
+ build: .
5
+ image: ccpa-compliance:latest
6
+ ports:
7
+ - "8000:8000"
8
+ environment:
9
+ - HF_TOKEN=${HF_TOKEN:-}
10
+ - MODEL_NAME=${MODEL_NAME:-llama3.2:3b}
11
+ deploy:
12
+ resources:
13
+ reservations:
14
+ devices:
15
+ - driver: nvidia
16
+ count: all
17
+ capabilities: [gpu]
18
+ restart: unless-stopped
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ fastapi==0.115.0
2
+ uvicorn[standard]==0.30.6
3
+ httpx==0.27.2
4
+ pydantic==2.9.2
settings.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "python-envs.defaultEnvManager": "ms-python.python:system"
3
+ }
start.sh ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -e
3
+
4
+ echo "========================================="
5
+ echo " CCPA Compliance Analyzer — Starting Up"
6
+ echo "========================================="
7
+
8
+ # ── Start Ollama in background ────────────────────────────────
9
+ echo "[1/3] Starting Ollama server..."
10
+ ollama serve &
11
+ OLLAMA_PID=$!
12
+
13
+ # ── Wait for Ollama to be ready ───────────────────────────────
14
+ echo "[2/3] Waiting for Ollama to become ready..."
15
+ MAX_WAIT=120
16
+ ELAPSED=0
17
+ until curl -sf http://localhost:11434/api/tags > /dev/null 2>&1; do
18
+ if [ $ELAPSED -ge $MAX_WAIT ]; then
19
+ echo "ERROR: Ollama did not start within ${MAX_WAIT}s. Exiting."
20
+ exit 1
21
+ fi
22
+ sleep 3
23
+ ELAPSED=$((ELAPSED + 3))
24
+ done
25
+ echo "Ollama is ready after ${ELAPSED}s."
26
+
27
+ # ── Verify model is available (already baked in during build) ─
28
+ MODEL="${MODEL_NAME:-llama3.2:3b}"
29
+ echo "Using model: $MODEL"
30
+ if ! ollama list | grep -q "$MODEL"; then
31
+ echo "Model not found in image — pulling now (fallback)..."
32
+ ollama pull "$MODEL"
33
+ fi
34
+
35
+ # ── Start FastAPI server ──────────────────────────────────────
36
+ echo "[3/3] Starting FastAPI server on port 8000..."
37
+ exec uvicorn app:app \
38
+ --host 0.0.0.0 \
39
+ --port 8000 \
40
+ --workers 1 \
41
+ --log-level info