Gokul commited on
Commit
586c48c
·
0 Parent(s):

Deploy Customs Officer Agent

Browse files
Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 1. Use Python 3.10 Slim
2
+ FROM python:3.10-slim
3
+
4
+ # 2. Set working directory
5
+ WORKDIR /app
6
+
7
+ # 3. Create a non-root user (Security requirement)
8
+ RUN useradd -m -u 1000 user
9
+ USER user
10
+ ENV PATH="/home/user/.local/bin:$PATH"
11
+
12
+ # 4. Install system dependencies for compiling llama-cpp
13
+ USER root
14
+ RUN apt-get update && apt-get install -y build-essential cmake
15
+ USER user
16
+
17
+ # 5. Install Python dependencies
18
+ COPY --chown=user requirements.txt .
19
+ RUN pip install --no-cache-dir --upgrade pip
20
+ # Force install CPU-optimized torch
21
+ RUN pip install --no-cache-dir torch --index-url https://download.pytorch.org/whl/cpu
22
+ # Install llama-cpp-python (CPU optimized)
23
+ RUN CMAKE_ARGS="-DGGML_BLAS=OFF" pip install --no-cache-dir llama-cpp-python
24
+ RUN pip install --no-cache-dir -r requirements.txt
25
+
26
+ # 6. Pre-download the "Embedding" Model (Fast Search)
27
+ RUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('all-mpnet-base-v2')"
28
+
29
+ # 7. Pre-download the "Reasoning" Model (The Customs Officer)
30
+ # We download the 4-bit Quantized version (~4.7GB)
31
+ RUN huggingface-cli download Qwen/Qwen2.5-7B-Instruct-GGUF qwen2.5-7b-instruct-q4_k_m.gguf --local-dir ./models --local-dir-use-symlinks False
32
+
33
+ # 8. Copy app code
34
+ COPY --chown=user . .
35
+
36
+ # 9. Start Server
37
+ CMD ["uvicorn", "api.index:app", "--host", "0.0.0.0", "--port", "7860"]
api/__pycache__/index.cpython-314.pyc ADDED
Binary file (7.32 kB). View file
 
api/index.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ print("⏳ Booting Beploo Audit-Grade Engine (Hypothesis Arbitration)...")
2
+
3
+ from fastapi import FastAPI
4
+ from fastapi.middleware.cors import CORSMiddleware
5
+ from pydantic import BaseModel
6
+ from sentence_transformers import SentenceTransformer, util
7
+ import torch
8
+ import re
9
+
10
+ app = FastAPI(title="Beploo Audit Engine")
11
+
12
+ app.add_middleware(
13
+ CORSMiddleware,
14
+ allow_origins=["*"],
15
+ allow_credentials=True,
16
+ allow_methods=["*"],
17
+ allow_headers=["*"],
18
+ )
19
+
20
+ # --- 1. LOAD MODEL ---
21
+ # The Judge.
22
+ model = SentenceTransformer('all-MiniLM-L6-v2')
23
+
24
+ # --- 2. THE 3 UNIVERSAL HYPOTHESES (The "Golden Standard") ---
25
+ # We encode these ONCE. These represent the three "buckets" every product falls into.
26
+
27
+ # H1: The Danger Bucket
28
+ RISK_DEFINITIONS = [
29
+ "Explosive bomb fireworks dynamite weapon gun firearm knife dagger sword ammunition",
30
+ "Hazardous toxic chemical poison acid battery lithium radioactive biohazard",
31
+ "Illegal narcotic drug controlled substance ivory endangered species"
32
+ ]
33
+
34
+ # H2: The Safety/Protection Bucket (The "Inverter")
35
+ # If an item falls here, it is SAFE, even if it mentions "Fire" or "Acid".
36
+ SAFETY_DEFINITIONS = [
37
+ "Personal protective equipment PPE helmet gloves goggles shield mask",
38
+ "Fire extinguisher safety suppression prevention rescue gear",
39
+ "Medical protection first aid sanitary hygiene",
40
+ "Child safety proofing guard lock barrier"
41
+ ]
42
+
43
+ # H3: The Benign Bucket (The Standard)
44
+ BENIGN_DEFINITIONS = [
45
+ "General consumer good household item furniture decor kitchenware",
46
+ "Childrens toy plush game puzzle education school supply",
47
+ "Clothing apparel textile fashion accessory shoes",
48
+ "Office supply electronics computer phone gadget tool hardware"
49
+ ]
50
+
51
+ print("🧠 Encoding Audit Standards...")
52
+ risk_vectors = model.encode(RISK_DEFINITIONS, convert_to_tensor=True)
53
+ safety_vectors = model.encode(SAFETY_DEFINITIONS, convert_to_tensor=True)
54
+ benign_vectors = model.encode(BENIGN_DEFINITIONS, convert_to_tensor=True)
55
+ print("✅ Audit Engine Ready.")
56
+
57
+ # --- 3. HARD REGEX (Only for 100% Binary Rules) ---
58
+ # We keep this ONLY for things that are illegal regardless of context (e.g. Ivory).
59
+ BINARY_BANS = [
60
+ {"id": "BAN_CITES", "pattern": r"(?i)\b(ivory|tiger|rhino|tortoise shell)\b", "desc": "BANNED: CITES Wildlife Product"},
61
+ {"id": "BAN_NARCOTIC", "pattern": r"(?i)\b(heroin|cocaine|meth|cannabis)\b", "desc": "BANNED: Narcotic Substance"}
62
+ ]
63
+
64
+ class ProductContext(BaseModel):
65
+ productName: str
66
+ description: str = ""
67
+ functionalUsecase: str = ""
68
+ commercialState: str = ""
69
+ proceduralUse: str = ""
70
+ material: str = ""
71
+ form: str = ""
72
+
73
+ @app.get("/")
74
+ def home():
75
+ return {"status": "online", "engine": "Hypothesis Arbitration (Audit Grade)"}
76
+
77
+ @app.post("/scan")
78
+ def scan_audit_grade(ctx: ProductContext):
79
+ # --- 1. CONSTRUCT THE "MANIFEST" ---
80
+ # We create a full, grammatically correct sentence for the AI to read.
81
+ # This helps the AI understand the *relationship* between words.
82
+ manifest_text = f"Item: {ctx.productName}. Material: {ctx.material}. Description: {ctx.description}. Use: {ctx.functionalUsecase}."
83
+ manifest_text = manifest_text.lower().strip()
84
+
85
+ print(f"\n👨‍⚖️ AUDITING: '{ctx.productName}'")
86
+
87
+ detected_risks = []
88
+
89
+ # --- 2. BINARY BAN CHECK (The "Zero Tolerance" Filter) ---
90
+ for ban in BINARY_BANS:
91
+ if re.search(ban["pattern"], manifest_text):
92
+ print(f" ⛔ CRITICAL BAN: {ban['desc']}")
93
+ return {
94
+ "status": "warning",
95
+ "matches": [{
96
+ "rule_id": ban["id"],
97
+ "risk_score": 100,
98
+ "warning": ban["desc"],
99
+ "handling_required": ["REJECT SHIPMENT"],
100
+ "source": "Global Ban List"
101
+ }],
102
+ "classification": ["Prohibited"]
103
+ }
104
+
105
+ # --- 3. HYPOTHESIS ARBITRATION (The Reasoning Engine) ---
106
+ if len(manifest_text) > 5:
107
+ query_vec = model.encode(manifest_text, convert_to_tensor=True)
108
+
109
+ # A. Score against Risk (H1)
110
+ risk_scores = util.cos_sim(query_vec, risk_vectors)[0]
111
+ max_risk = float(torch.max(risk_scores))
112
+
113
+ # B. Score against Safety (H2)
114
+ safety_scores = util.cos_sim(query_vec, safety_vectors)[0]
115
+ max_safety = float(torch.max(safety_scores))
116
+
117
+ # C. Score against Benign (H3)
118
+ benign_scores = util.cos_sim(query_vec, benign_vectors)[0]
119
+ max_benign = float(torch.max(benign_scores))
120
+
121
+ print(f" 📊 SCORES -> Risk: {int(max_risk*100)} | Safety: {int(max_safety*100)} | Benign: {int(max_benign*100)}")
122
+
123
+ # --- THE JUDGMENT LOGIC ---
124
+
125
+ # Scenario A: It's definitely Safe/Benign
126
+ # If Safety OR Benign is significantly higher than Risk, we clear it.
127
+ # "Significantly" = 10% margin.
128
+ if (max_safety > max_risk + 0.10) or (max_benign > max_risk + 0.10):
129
+ print(" ✅ VERDICT: SAFE (Protective/Benign context overrides Risk)")
130
+ return {"status": "clean", "message": "Cleared: Valid Commercial Good", "classification": ["General Cargo"]}
131
+
132
+ # Scenario B: It's Ambiguous or Risky
133
+ # If Risk is the winner OR it's very close to the others (Ambiguous)
134
+ if max_risk > 0.35: # Base suspicion threshold
135
+
136
+ # Sub-Check: Is it "Lithium"? (Batteries are special - they are Risky AND Benign)
137
+ # If "Battery" is the risk driver, we must flag it for labeling, even if it's a "Benign Phone".
138
+ if "battery" in manifest_text or "lithium" in manifest_text:
139
+ detected_risks.append({
140
+ "rule_id": "DG_BATTERY",
141
+ "risk_score": int(max_risk * 100),
142
+ "warning": "Contains Batteries (Lithium/Dry Cell). UN3480/UN3481 labeling required.",
143
+ "handling_required": ["DG Declaration"],
144
+ "source": "Audit Reasoning"
145
+ })
146
+
147
+ # Sub-Check: Is it a Weapon?
148
+ elif max_risk > max_safety and max_risk > max_benign:
149
+ detected_risks.append({
150
+ "rule_id": "RES_WEAPON",
151
+ "risk_score": int(max_risk * 100),
152
+ "warning": "High Probability of Weapon / Restricted Item.",
153
+ "handling_required": ["Import License", "Manual Inspection"],
154
+ "source": "Audit Reasoning"
155
+ })
156
+
157
+ # Sub-Check: Is it Chemical?
158
+ elif "acid" in manifest_text or "chemical" in manifest_text:
159
+ # Double check: Did Safety lose?
160
+ if max_safety < max_risk:
161
+ detected_risks.append({
162
+ "rule_id": "DG_CHEMICAL",
163
+ "risk_score": int(max_risk * 100),
164
+ "warning": "Hazardous Chemical detected.",
165
+ "handling_required": ["MSDS Required"],
166
+ "source": "Audit Reasoning"
167
+ })
168
+
169
+ # --- 4. RETURN VERDICT ---
170
+ if detected_risks:
171
+ return {"status": "warning", "matches": detected_risks, "classification": ["Restricted / DG"]}
172
+
173
+ return {"status": "clean", "message": "Audit Passed", "classification": ["General Cargo"]}
174
+
175
+ if __name__ == "__main__":
176
+ import uvicorn
177
+ uvicorn.run(app, host="127.0.0.1", port=8000)
beploo_diagnostics_full.json ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "meta": {
3
+ "dataset_version": "1.0.0",
4
+ "generated_at": "2026-02-10 21:01:55.763067",
5
+ "standard_references": [
6
+ "IATA-DGR",
7
+ "CITES",
8
+ "HACCP",
9
+ "Global-Customs"
10
+ ],
11
+ "total_rules": 10
12
+ },
13
+ "rules": [
14
+ {
15
+ "id": "DG_001_LITHIUM",
16
+ "category": "Dangerous Goods",
17
+ "risk_score": 90,
18
+ "match_type": "strict",
19
+ "requires_handling": [
20
+ "UN3480",
21
+ "UN3481",
22
+ "Cargo Aircraft Only"
23
+ ],
24
+ "description": "Contains Lithium Batteries. Strict air transport regulations apply.",
25
+ "keywords": [
26
+ "lithium ion",
27
+ "lithium metal",
28
+ "lipo battery",
29
+ "18650",
30
+ "power bank",
31
+ "mah",
32
+ "cr2032",
33
+ "button cell"
34
+ ]
35
+ },
36
+ {
37
+ "id": "DG_002_FLAMMABLE_LIQ",
38
+ "category": "Dangerous Goods",
39
+ "risk_score": 85,
40
+ "match_type": "broad",
41
+ "requires_handling": [
42
+ "Flammable Liquid Label",
43
+ "Limited Quantity"
44
+ ],
45
+ "description": "Flammable liquid (Class 3). Flash point checks required.",
46
+ "keywords": [
47
+ "ethanol",
48
+ "alcohol",
49
+ "acetone",
50
+ "varnish",
51
+ "paint thinner",
52
+ "gasoline",
53
+ "fuel",
54
+ "lighter fluid",
55
+ "perfume concentrate"
56
+ ]
57
+ },
58
+ {
59
+ "id": "DG_003_AEROSOLS",
60
+ "category": "Dangerous Goods",
61
+ "risk_score": 80,
62
+ "match_type": "broad",
63
+ "requires_handling": [
64
+ "Pressure Vessel",
65
+ "Keep Away from Heat"
66
+ ],
67
+ "description": "Compressed gas/Aerosols (Class 2). Explosion hazard if heated.",
68
+ "keywords": [
69
+ "aerosol",
70
+ "spray can",
71
+ "compressed gas",
72
+ "butane",
73
+ "propane",
74
+ "hairspray",
75
+ "deodorant spray"
76
+ ]
77
+ },
78
+ {
79
+ "id": "DG_004_MAGNETIZED",
80
+ "category": "Dangerous Goods",
81
+ "risk_score": 60,
82
+ "match_type": "strict",
83
+ "requires_handling": [
84
+ "Magnetic Field Check"
85
+ ],
86
+ "description": "Magnetized material which may interfere with aircraft navigation.",
87
+ "keywords": [
88
+ "neodymium",
89
+ "strong magnet",
90
+ "subwoofer",
91
+ "loudspeaker",
92
+ "magnetron",
93
+ "mri component"
94
+ ]
95
+ },
96
+ {
97
+ "id": "RES_001_WILDLIFE",
98
+ "category": "Restricted Materials",
99
+ "risk_score": 100,
100
+ "match_type": "strict",
101
+ "requires_handling": [
102
+ "CITES Permit",
103
+ "Origin Certificate"
104
+ ],
105
+ "description": "Potential endangered species material. Trade heavily regulated.",
106
+ "keywords": [
107
+ "ivory",
108
+ "tortoiseshell",
109
+ "reptile skin",
110
+ "crocodile leather",
111
+ "coral",
112
+ "rosewood",
113
+ "teak",
114
+ "shark fin"
115
+ ]
116
+ },
117
+ {
118
+ "id": "RES_002_WEAPONRY",
119
+ "category": "Restricted Materials",
120
+ "risk_score": 100,
121
+ "match_type": "strict",
122
+ "requires_handling": [
123
+ "Import License",
124
+ "Age Verification"
125
+ ],
126
+ "description": "Weapons or weapon parts. potential localized restrictions.",
127
+ "keywords": [
128
+ "knife",
129
+ "blade",
130
+ "sword",
131
+ "dagger",
132
+ "firearm",
133
+ "ammo",
134
+ "tactical gear",
135
+ "gun part",
136
+ "scope",
137
+ "hunting bow"
138
+ ]
139
+ },
140
+ {
141
+ "id": "RES_003_DRUGS_MEDS",
142
+ "category": "Restricted Materials",
143
+ "risk_score": 95,
144
+ "match_type": "contextual",
145
+ "requires_handling": [
146
+ "Prescription",
147
+ "FDA/EMA Approval"
148
+ ],
149
+ "description": "Pharmaceuticals or controlled substances.",
150
+ "keywords": [
151
+ "prescription",
152
+ "drug",
153
+ "pharmacy",
154
+ "medication",
155
+ "pills",
156
+ "antibiotic",
157
+ "cbd",
158
+ "hemp",
159
+ "supplement"
160
+ ]
161
+ },
162
+ {
163
+ "id": "HND_001_FRAGILE",
164
+ "category": "Handling",
165
+ "risk_score": 40,
166
+ "match_type": "broad",
167
+ "requires_handling": [
168
+ "Fragile Label",
169
+ "Double Boxing"
170
+ ],
171
+ "description": "Items prone to breakage during transit.",
172
+ "keywords": [
173
+ "glass",
174
+ "ceramic",
175
+ "porcelain",
176
+ "mirror",
177
+ "monitor",
178
+ "screen",
179
+ "tv",
180
+ "vase",
181
+ "china",
182
+ "crystal"
183
+ ]
184
+ },
185
+ {
186
+ "id": "HND_002_PERISHABLE",
187
+ "category": "Handling",
188
+ "risk_score": 75,
189
+ "match_type": "strict",
190
+ "requires_handling": [
191
+ "Cold Chain",
192
+ "Expedited Shipping"
193
+ ],
194
+ "description": "Goods with limited shelf life or temperature sensitivity.",
195
+ "keywords": [
196
+ "food",
197
+ "chocolate",
198
+ "frozen",
199
+ "fresh",
200
+ "meat",
201
+ "cheese",
202
+ "plant",
203
+ "flower",
204
+ "live animal"
205
+ ]
206
+ },
207
+ {
208
+ "id": "HND_003_OVERSIZE",
209
+ "category": "Handling",
210
+ "risk_score": 50,
211
+ "match_type": "broad",
212
+ "requires_handling": [
213
+ "Freight Shipping",
214
+ "Lift Gate"
215
+ ],
216
+ "description": "Likely heavy or bulky items requiring special logistics.",
217
+ "keywords": [
218
+ "furniture",
219
+ "sofa",
220
+ "bed",
221
+ "mattress",
222
+ "treadmill",
223
+ "generator",
224
+ "engine",
225
+ "kayak",
226
+ "surfboard"
227
+ ]
228
+ }
229
+ ]
230
+ }
requirements.txt ADDED
Binary file (2.65 kB). View file
 
vercel.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "builds": [
3
+ {
4
+ "src": "api/index.py",
5
+ "use": "@vercel/python"
6
+ }
7
+ ],
8
+ "routes": [
9
+ {
10
+ "src": "/(.*)",
11
+ "dest": "api/index.py"
12
+ }
13
+ ]
14
+ }