Sumayyea commited on
Commit
8998caa
Β·
verified Β·
1 Parent(s): 33cc687

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +228 -149
app.py CHANGED
@@ -1,152 +1,231 @@
 
 
 
 
 
 
1
  import streamlit as st
2
- import re
3
- from datetime import datetime
4
- from typing import Dict, Any, List
5
-
6
-
7
- # -------------------------
8
- # Document Classifier Class
9
- # -------------------------
10
-
11
- class DocumentClassifier:
12
- """
13
- AI Document Classification System for Government E-Filing
14
-
15
- This class demonstrates how AI can automatically classify government documents
16
- into predefined categories based on content analysis.
17
- """
18
-
19
- def __init__(self):
20
- self.categories = {
21
- 'ADMINISTRATIVE': ['memo', 'circular', 'notification', 'order', 'policy'],
22
- 'FINANCIAL': ['budget', 'expenditure', 'audit', 'payment', 'revenue'],
23
- 'LEGAL': ['contract', 'agreement', 'legal', 'court', 'judgment'],
24
- 'HR': ['recruitment', 'promotion', 'transfer', 'leave', 'employee'],
25
- 'TECHNICAL': ['specification', 'tender', 'project', 'development', 'infrastructure']
26
- }
27
- self.confidence_threshold = 0.7
28
- print("Document Classifier initialized with government document categories")
29
-
30
- def extract_features(self, document_text: str) -> Dict[str, Any]:
31
- """Extract features from document text for classification"""
32
- text_lower = document_text.lower()
33
- features = {}
34
-
35
- # Count occurrences of category-specific keywords
36
- for category, keywords in self.categories.items():
37
- feature_count = sum(text_lower.count(keyword) for keyword in keywords)
38
- features[f'{category}_score'] = feature_count
39
-
40
- features['word_count'] = len(text_lower.split())
41
-
42
- # Date extraction
43
- date_patterns = [
44
- r'\b\d{1,2}[-/]\d{1,2}[-/]\d{4}\b',
45
- r'\b\d{1,2}(?:st|nd|rd|th)?\s+[A-Z][a-z]+,\s+\d{4}\b',
46
- r'\b\d{1,2}(?:st|nd|rd|th)?\s+[A-Z][a-z]+\s+\d{4}\b',
47
- r'\b[A-Z][a-z]+\s+\d{1,2},\s+\d{4}\b'
48
- ]
49
- found_date = None
50
- for pattern in date_patterns:
51
- match = re.search(pattern, document_text)
52
- if match:
53
- found_date = match.group()
54
- break
55
- features['has_date'] = 1 if found_date else 0
56
- features['extracted_date'] = found_date if found_date else "N/A"
57
-
58
- # Reference number extraction
59
- ref_patterns = [
60
- r'\bref(?:\.|\s|:)*[A-Za-z0-9/\-()]+',
61
- r'\bno(?:\.|\s|:)*[A-Za-z0-9/\-()]+'
62
- ]
63
- found_ref = None
64
- for pattern in ref_patterns:
65
- match = re.search(pattern, document_text, flags=re.IGNORECASE)
66
- if match:
67
- found_ref = match.group().strip()
68
- break
69
- features['has_reference'] = 1 if found_ref else 0
70
- features['extracted_reference'] = found_ref if found_ref else "N/A"
71
-
72
- return features
73
-
74
- def classify_document(self, document_text: str, filename: str = "") -> Dict[str, Any]:
75
- """Classify a document using AI-based content analysis"""
76
- features = self.extract_features(document_text)
77
- scores = {}
78
-
79
- for category in self.categories:
80
- score_key = f'{category}_score'
81
- base_score = features.get(score_key, 0)
82
- normalized_score = base_score / max(features['word_count'] / 100, 1)
83
- scores[category] = normalized_score
84
-
85
- best_category = max(scores, key=scores.get)
86
- confidence = min(scores[best_category] / 5.0, 1.0)
87
-
88
- return {
89
- 'filename': filename,
90
- 'predicted_category': best_category,
91
- 'confidence': confidence,
92
- 'all_scores': scores,
93
- 'classification_date': datetime.now().isoformat(),
94
- 'features': features
95
  }
96
 
97
- def batch_classify(self, documents: List[Dict[str, str]]) -> List[Dict[str, Any]]:
98
- """Classify multiple documents in batch"""
99
- results = []
100
- for doc in documents:
101
- result = self.classify_document(doc['content'], doc.get('filename', ''))
102
- results.append(result)
103
- print(f"Batch classification completed for {len(documents)} documents")
104
- return results
105
-
106
-
107
- # -------------------------
108
- # Streamlit App UI
109
- # -------------------------
110
-
111
- st.set_page_config(page_title="AI Document Classifier", layout="centered")
112
- st.title("πŸ“„ AI-Based Document Classifier")
113
- st.subheader("Upload government text files for automatic classification")
114
-
115
- uploaded_files = st.file_uploader(
116
- "Choose .txt files", type=["txt"], accept_multiple_files=True
117
- )
118
-
119
- if uploaded_files:
120
- classifier = DocumentClassifier()
121
-
122
- # Read all files for batch processing
123
- docs = []
124
- for uploaded_file in uploaded_files:
125
- filename = uploaded_file.name
126
- content = uploaded_file.read().decode("utf-8")
127
- docs.append({"filename": filename, "content": content})
128
-
129
- results = classifier.batch_classify(docs)
130
-
131
- # Display results per document
132
- for result in results:
133
- st.markdown("---")
134
- st.markdown(f"πŸ“ **Document:** `{result['filename']}`")
135
- st.markdown(f"πŸ“‚ **Predicted Category:** `{result['predicted_category']}`")
136
- st.markdown(f"πŸ“Š **Confidence:** `{result['confidence']:.2f}`")
137
-
138
- # Extracted metadata
139
- extracted_date = result["features"].get("extracted_date", "N/A")
140
- extracted_ref = result["features"].get("extracted_reference", "N/A")
141
-
142
- col1, col2 = st.columns(2)
143
- with col1:
144
- st.markdown(f"πŸ—“οΈ **Extracted Date:** `{extracted_date}`")
145
- with col2:
146
- st.markdown(f"πŸ“Ž **Reference Number:** `{extracted_ref}`")
147
-
148
- with st.expander("πŸ” Feature Details", expanded=False):
149
- st.json(result['features'])
150
-
151
- with st.expander("πŸ“œ Full Text", expanded=False):
152
- st.text(next(doc['content'] for doc in docs if doc['filename'] == result['filename']))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, re, json, time, hashlib
2
+ from io import BytesIO
3
+ from concurrent.futures import ThreadPoolExecutor, as_completed
4
+
5
+ import pandas as pd
6
+ import requests
7
  import streamlit as st
8
+
9
+ # ─────────────────────────────────────────────
10
+ # 1. CONFIGURATION
11
+ # ─────────────────────────────────────────────
12
+ CATEGORIES = {
13
+ "ADMINISTRATIVE": {"desc": "Notifications, circulars, office orders, memos, meeting minutes, policy instructions",
14
+ "keywords": ["memo", "circular", "notification", "order", "policy", "minutes", "meeting", "instruction"]},
15
+ "FINANCIAL": {"desc": "Budget, expenditure, audit, payments, bills, revenue, re-appropriation, PC-1 costing",
16
+ "keywords": ["budget", "expenditure", "audit", "payment", "revenue", "bill", "fund", "grant", "rupees", "allocation"]},
17
+ "LEGAL": {"desc": "Contracts, agreements, court cases, writ petitions, judgments, legal opinions",
18
+ "keywords": ["contract", "agreement", "legal", "court", "judgment", "petition", "writ", "tribunal", "litigation"]},
19
+ "HR": {"desc": "Recruitment, promotion, transfer/posting, leave, pension, disciplinary matters",
20
+ "keywords": ["recruitment", "promotion", "transfer", "posting", "leave", "employee", "pension", "appointment", "seniority"]},
21
+ "TECHNICAL": {"desc": "Tenders, specifications, development projects, IT systems, infrastructure",
22
+ "keywords": ["specification", "tender", "project", "development", "infrastructure", "procurement", "software", "construction"]},
23
+ "CITIZEN_SERVICE": {"desc": "Citizen applications, complaints, NOCs, requests, grievances",
24
+ "keywords": ["complaint", "grievance", "noc", "objection", "applicant", "citizen", "request", "redressal"]},
25
+ }
26
+
27
+ OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
28
+ DEFAULT_MODEL = "openai/gpt-4o-mini" # check current IDs at openrouter.ai/models
29
+
30
+ # ─────────────────────────────────────────────
31
+ # 2. RULE-BASED ENGINE (optimized v1)
32
+ # ─────────────────────────────────────────────
33
+ class RuleClassifier:
34
+ """Precompiled, word-boundary regex -> no false hits ('order' in 'border')."""
35
+
36
+ def __init__(self, categories):
37
+ self.patterns = {
38
+ cat: re.compile(r"\b(?:" + "|".join(map(re.escape, v["keywords"])) + r")\w*\b", re.IGNORECASE)
39
+ for cat, v in categories.items()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  }
41
 
42
+ def classify(self, text):
43
+ hits = {cat: len(p.findall(text)) for cat, p in self.patterns.items()}
44
+ total = sum(hits.values())
45
+ if total == 0:
46
+ return {"category": "UNCLASSIFIED", "confidence": 0.0, "scores": hits}
47
+ best = max(hits, key=hits.get)
48
+ return {"category": best, "confidence": round(hits[best] / total, 2), "scores": hits}
49
+
50
+
51
+ MONTHS = r"(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*"
52
+ DATE_RE = re.compile(
53
+ rf"\b(?P<d>\d{{1,2}}(?P<s>[./-])\d{{1,2}}(?P=s)\d{{2,4}}"
54
+ rf"|\d{{1,2}}(?:st|nd|rd|th)?\s+{MONTHS},?\s+\d{{4}}"
55
+ rf"|{MONTHS}\s+\d{{1,2}},?\s+\d{{4}})\b", re.IGNORECASE)
56
+ # Reference must contain a digit -> "No objection" is NOT a reference
57
+ REF_RE = re.compile(r"\b(?:Ref(?:erence)?|File|Letter|Endst|No)\.?\s*(?:No\.?)?\s*[:#]?\s*"
58
+ r"([A-Z0-9][\w/&().\-]*\d[\w/&().\-]*)", re.IGNORECASE)
59
+
60
+ def extract_metadata(text):
61
+ d, r = DATE_RE.search(text), REF_RE.search(text)
62
+ return {"date": d.group("d") if d else None, "reference_no": r.group(1).rstrip(".") if r else None}
63
+
64
+ # ─────────────────────────────────────────────
65
+ # 3. PRIVACY: redact before sending to external AI
66
+ # ─────────────────────────────────────────────
67
+ PII_PATTERNS = {
68
+ "CNIC": re.compile(r"\b\d{5}-?\d{7}-?\d\b"),
69
+ "PHONE": re.compile(r"(?:\+92|\b0)3\d{2}[-\s]?\d{7}\b"),
70
+ "EMAIL": re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+"),
71
+ }
72
+
73
+ def redact(text):
74
+ for label, pattern in PII_PATTERNS.items():
75
+ text = pattern.sub(f"[{label}]", text)
76
+ return text
77
+
78
+ # ─────────────────────────────────────────────
79
+ # 4. TEXT EXTRACTION (txt / pdf / docx)
80
+ # ─────────────────────────────────────────────
81
+ def extract_text(name, data):
82
+ ext = name.lower().rsplit(".", 1)[-1]
83
+ if ext == "txt":
84
+ return data.decode("utf-8", errors="ignore")
85
+ if ext == "pdf":
86
+ from pypdf import PdfReader
87
+ return "\n".join((p.extract_text() or "") for p in PdfReader(BytesIO(data)).pages)
88
+ if ext == "docx":
89
+ from docx import Document
90
+ return "\n".join(p.text for p in Document(BytesIO(data)).paragraphs)
91
+ return ""
92
+
93
+ # ─────────────────────────────────────────────
94
+ # 5. AI ENGINE (OpenRouter)
95
+ # ─────────────────────────────────────────────
96
+ CAT_LIST = "\n".join(f"- {c}: {v['desc']}" for c, v in CATEGORIES.items())
97
+ SYSTEM_PROMPT = f"""You are a records officer AI for the Government of Khyber Pakhtunkhwa, Pakistan.
98
+ Classify the document into exactly ONE category:
99
+ {CAT_LIST}
100
+ Documents may be English, Urdu or mixed, and may contain OCR errors.
101
+ Return ONLY valid JSON with these keys:
102
+ {{"category": "<one of the categories>", "confidence": <0.0-1.0>, "reason": "<one sentence>",
103
+ "subject": "<short subject line>", "summary": "<max 2 sentences>",
104
+ "date": "<date or null>", "reference_no": "<file/letter no. or null>",
105
+ "department": "<issuing department or null>", "urgency": "Immediate|High|Normal",
106
+ "action_required": "<what the receiving officer must do, or null>", "language": "English|Urdu|Mixed"}}"""
107
+
108
+ def parse_json(content):
109
+ content = re.sub(r"```(?:json)?", "", content).strip()
110
+ start, end = content.find("{"), content.rfind("}")
111
+ return json.loads(content[start:end + 1])
112
+
113
+ def llm_classify(text, api_key, model, max_chars=6000):
114
+ headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json",
115
+ "HTTP-Referer": "http://localhost:8501", "X-Title": "KP Document Classifier"}
116
+ payload = {
117
+ "model": model, "temperature": 0,
118
+ "response_format": {"type": "json_object"},
119
+ "messages": [{"role": "system", "content": SYSTEM_PROMPT},
120
+ {"role": "user", "content": text[:max_chars]}], # truncate = faster + cheaper
121
+ }
122
+ for attempt in range(3): # retry on rate-limit / server error
123
+ r = requests.post(OPENROUTER_URL, headers=headers, json=payload, timeout=60)
124
+ if r.status_code == 429 or r.status_code >= 500:
125
+ time.sleep(2 ** attempt)
126
+ continue
127
+ r.raise_for_status()
128
+ data = parse_json(r.json()["choices"][0]["message"]["content"])
129
+ if data.get("category") not in CATEGORIES:
130
+ data["category"] = "UNCLASSIFIED"
131
+ data["confidence"] = max(0.0, min(1.0, float(data.get("confidence", 0))))
132
+ return data
133
+ raise RuntimeError("OpenRouter busy β€” retried 3 times")
134
+
135
+ # ─────────────────────────────────────────────
136
+ # 6. HYBRID PIPELINE
137
+ # ─────────────────────────────────────────────
138
+ @st.cache_resource
139
+ def get_engine():
140
+ return RuleClassifier(CATEGORIES), {} # {} = AI response cache (survives reruns)
141
+
142
+ def classify_one(name, text, cfg, rules, cache):
143
+ t0 = time.perf_counter()
144
+ rule, meta = rules.classify(text), extract_metadata(text)
145
+ res = {"file": name, "words": len(text.split()), "method": "Rule-based",
146
+ "category": rule["category"], "confidence": rule["confidence"],
147
+ "rule_scores": rule["scores"], **meta}
148
+
149
+ if not text.strip():
150
+ res["method"] = "Skipped (no text β€” run OCR Processor first)"
151
+ elif cfg["use_ai"] and cfg["api_key"] and (cfg["always_ai"] or rule["confidence"] < cfg["threshold"]):
152
+ safe_text = redact(text) if cfg["redact"] else text
153
+ key = hashlib.sha256((cfg["model"] + safe_text).encode()).hexdigest()
154
+ try:
155
+ ai = cache.get(key) or llm_classify(safe_text, cfg["api_key"], cfg["model"])
156
+ cache[key] = ai
157
+ res.update({k: v for k, v in ai.items() if v not in (None, "", "null")})
158
+ res["method"] = "AI (OpenRouter)"
159
+ except Exception as e:
160
+ res["method"], res["error"] = "Rule-based (AI failed)", str(e)
161
+
162
+ res["latency_s"] = round(time.perf_counter() - t0, 2)
163
+ return res
164
+
165
+ # ─────────────────────────────────────────────
166
+ # 7. STREAMLIT UI
167
+ # ─────────────────────────────────────────────
168
+ def default_key():
169
+ try:
170
+ return st.secrets["OPENROUTER_API_KEY"]
171
+ except Exception:
172
+ return os.getenv("OPENROUTER_API_KEY", "")
173
+
174
+ st.set_page_config(page_title="AI Document Classifier v2", page_icon="πŸ“„", layout="wide")
175
+ st.title("πŸ“„ AI Document Classifier v2")
176
+ st.caption("Hybrid Rule-based + AI (OpenRouter) β€’ KP Digital Roadmap 2030 β€” Paperless Government Processes")
177
+
178
+ with st.sidebar:
179
+ st.header("βš™οΈ Settings")
180
+ cfg = {
181
+ "api_key": st.text_input("OpenRouter API Key", value=default_key(), type="password"),
182
+ "model": st.text_input("Model", value=DEFAULT_MODEL),
183
+ "use_ai": st.toggle("Use AI", value=True),
184
+ "always_ai": st.toggle("Always use AI (else only when rules unsure)", value=False),
185
+ "threshold": st.slider("Rule confidence needed to skip AI", 0.3, 1.0, 0.7, 0.05),
186
+ "redact": st.toggle("πŸ”’ Redact CNIC / phone / email before AI", value=True),
187
+ "workers": st.slider("Parallel workers", 1, 10, 4),
188
+ }
189
+ if cfg["use_ai"] and not cfg["api_key"]:
190
+ st.warning("No API key β€” running rule-based only.")
191
+
192
+ files = st.file_uploader("Upload documents", type=["txt", "pdf", "docx"], accept_multiple_files=True)
193
+
194
+ if files and st.button("πŸš€ Classify", type="primary"):
195
+ rules, cache = get_engine()
196
+ docs = {f.name: extract_text(f.name, f.getvalue()) for f in files}
197
+
198
+ results, bar, t0 = [], st.progress(0.0, "Classifying..."), time.perf_counter()
199
+ with ThreadPoolExecutor(max_workers=cfg["workers"]) as pool:
200
+ futures = [pool.submit(classify_one, n, t, cfg, rules, cache) for n, t in docs.items()]
201
+ for i, fut in enumerate(as_completed(futures), 1):
202
+ results.append(fut.result())
203
+ bar.progress(i / len(futures), f"{i}/{len(futures)} done")
204
+ total_time = time.perf_counter() - t0
205
+
206
+ df = pd.DataFrame(results)
207
+ c1, c2, c3, c4 = st.columns(4)
208
+ c1.metric("Documents", len(df))
209
+ c2.metric("AI calls", int(df["method"].eq("AI (OpenRouter)").sum()))
210
+ c3.metric("Total time", f"{total_time:.1f}s")
211
+ c4.metric("Avg confidence", f"{df['confidence'].mean():.0%}")
212
+
213
+ cols = [c for c in ["file", "category", "confidence", "method", "subject", "urgency",
214
+ "date", "reference_no", "department", "action_required", "latency_s"] if c in df]
215
+ st.dataframe(df[cols], use_container_width=True, hide_index=True)
216
+ st.bar_chart(df["category"].value_counts())
217
+
218
+ low = df[df["confidence"] < 0.6]
219
+ if not low.empty:
220
+ st.warning(f"πŸ‘€ {len(low)} document(s) below 60% confidence β€” route for human review.")
221
+
222
+ for r in results:
223
+ with st.expander(f"πŸ“ {r['file']} β†’ {r['category']} ({r['confidence']:.0%})"):
224
+ if r.get("summary"): st.info(r["summary"])
225
+ if r.get("reason"): st.caption(f"Why: {r['reason']}")
226
+ if r.get("error"): st.error(r["error"])
227
+ st.json({k: v for k, v in r.items() if k not in ("summary", "reason")})
228
+ st.text_area("Text", docs[r["file"]][:3000], height=150, key=f"t_{r['file']}")
229
+
230
+ st.download_button("⬇️ Download results (CSV)", df[cols].to_csv(index=False).encode("utf-8"),
231
+ "classification_results.csv", "text/csv")