asad231 commited on
Commit
d68601a
Β·
verified Β·
1 Parent(s): 620d262

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +191 -0
app.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PIL import Image
3
+ import numpy as np
4
+ import pandas as pd
5
+ import tempfile
6
+ import folium
7
+ from reportlab.pdfgen import canvas
8
+ from ultralytics import YOLO
9
+ from transformers import pipeline
10
+ import zipfile
11
+ import os
12
+ from streamlit_folium import st_folium
13
+
14
+ # ===========================================
15
+ # LOAD MODELS
16
+ # ===========================================
17
+ detection_model = YOLO("yolov5s.pt")
18
+ summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
19
+
20
+ # ===========================================
21
+ # GLOBAL STORAGE
22
+ # ===========================================
23
+ if "history" not in st.session_state:
24
+ st.session_state.history = []
25
+
26
+ if "incident_counter" not in st.session_state:
27
+ st.session_state.incident_counter = 1
28
+
29
+
30
+ # ===========================================
31
+ # HELPERS
32
+ # ===========================================
33
+ def generate_incident_id():
34
+ code = f"IG-2025-{st.session_state.incident_counter:05d}"
35
+ st.session_state.incident_counter += 1
36
+ return code
37
+
38
+
39
+ def severity_badge(sev):
40
+ colors = {"High": "red", "Medium": "orange", "Low": "green"}
41
+ return f"<span style='padding:6px 12px;border-radius:6px;background:{colors[sev]};color:white;font-weight:bold'>{sev}</span>"
42
+
43
+
44
+ def create_pdf(objects, severity, summary, lat, lon, incident_id):
45
+ f = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
46
+ c = canvas.Canvas(f.name)
47
+
48
+ c.setFont("Helvetica-Bold", 18)
49
+ c.drawString(100, 800, f"InfraGuard Incident Report")
50
+
51
+ c.setFont("Helvetica", 12)
52
+ c.drawString(100, 770, f"Incident ID: {incident_id}")
53
+ c.drawString(100, 750, f"Objects: {objects}")
54
+ c.drawString(100, 730, f"Severity: {severity}")
55
+ c.drawString(100, 710, f"Summary: {summary}")
56
+ c.drawString(100, 690, f"Location: {lat}, {lon}")
57
+
58
+ c.save()
59
+ return f.name
60
+
61
+
62
+ def analyze(img, lat, lon):
63
+ img_np = np.array(img)
64
+ results = detection_model.predict(img_np, imgsz=640)
65
+
66
+ objs = [detection_model.names[int(b.cls)] for b in results[0].boxes]
67
+ objects_text = ", ".join(objs) if objs else "None"
68
+
69
+ # Severity
70
+ severity = "Low"
71
+ if "fire" in objs:
72
+ severity = "High"
73
+ elif any(x in objs for x in ["car", "truck", "bus"]):
74
+ severity = "Medium"
75
+
76
+ # AI summary
77
+ story = f"Detected objects: {objects_text}. Severity: {severity}."
78
+ try:
79
+ summary = summarizer(story, max_length=40, min_length=10)[0]["summary_text"]
80
+ except:
81
+ summary = story
82
+
83
+ # Annotated image
84
+ annotated = Image.fromarray(results[0].plot())
85
+
86
+ incident_id = generate_incident_id()
87
+ pdf_file = create_pdf(objects_text, severity, summary, lat, lon, incident_id)
88
+
89
+ # Save original image
90
+ thumb = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
91
+ img.save(thumb.name)
92
+
93
+ entry = {
94
+ "ID": incident_id,
95
+ "Image": thumb.name,
96
+ "Objects": objects_text,
97
+ "Severity": severity,
98
+ "Summary": summary,
99
+ "Latitude": lat,
100
+ "Longitude": lon,
101
+ "PDF": pdf_file
102
+ }
103
+ st.session_state.history.append(entry)
104
+
105
+ return annotated, summary, severity, pdf_file, entry
106
+
107
+
108
+ def download_all():
109
+ if not st.session_state.history:
110
+ return None
111
+
112
+ zip_path = tempfile.NamedTemporaryFile(delete=False, suffix=".zip").name
113
+ with zipfile.ZipFile(zip_path, "w") as z:
114
+ for h in st.session_state.history:
115
+ z.write(h["PDF"], os.path.basename(h["PDF"]))
116
+ return zip_path
117
+
118
+
119
+ # ===========================================
120
+ # PAGE THEME / CSS
121
+ # ===========================================
122
+ st.markdown("""
123
+ <style>
124
+ body { background:#03121f !important; }
125
+ h1 { color:#00eaff; text-align:center; }
126
+ .reportview-container .main { background:#03121f; color:white; }
127
+ .sidebar .sidebar-content { background:#021018; }
128
+ </style>
129
+ """, unsafe_allow_html=True)
130
+
131
+ # ===========================================
132
+ # UI LAYOUT
133
+ # ===========================================
134
+ st.title("🚨 INFRA GUARD – Cyber Security AI Dashboard")
135
+
136
+ tab1, tab2 = st.tabs(["πŸ” Analyze Incident", "πŸ“ Incident History"])
137
+
138
+ # -----------------------------------------------------
139
+ # TAB 1: ANALYZE INCIDENT
140
+ # -----------------------------------------------------
141
+ with tab1:
142
+ img_file = st.file_uploader("Upload Image", type=["jpg", "png", "jpeg"])
143
+ lat = st.number_input("Latitude", value=24.8607)
144
+ lon = st.number_input("Longitude", value=67.0011)
145
+
146
+ if st.button("Analyze"):
147
+ if img_file is not None:
148
+ img = Image.open(img_file)
149
+
150
+ annotated, summary, severity, pdf_path, entry = analyze(img, lat, lon)
151
+
152
+ st.subheader("Annotated Image")
153
+ st.image(annotated)
154
+
155
+ st.subheader("AI Summary")
156
+ st.write(summary)
157
+
158
+ st.subheader("Severity")
159
+ st.markdown(severity_badge(severity), unsafe_allow_html=True)
160
+
161
+ st.subheader("Download PDF Report")
162
+ with open(pdf_path, "rb") as f:
163
+ st.download_button("Download PDF", f, file_name=f"{entry['ID']}.pdf")
164
+
165
+ # Map
166
+ m = folium.Map(location=[lat, lon], zoom_start=15)
167
+ folium.Marker([lat, lon]).add_to(m)
168
+ st_folium(m, width=700, height=350)
169
+
170
+ st.success("Incident Added to History!")
171
+
172
+ # -----------------------------------------------------
173
+ # TAB 2: HISTORY TABLE
174
+ # -----------------------------------------------------
175
+ with tab2:
176
+ if st.session_state.history:
177
+ df = pd.DataFrame(st.session_state.history)
178
+ st.dataframe(df)
179
+
180
+ del_index = st.number_input("Delete Row (Index)", min_value=0, max_value=len(df)-1, step=1)
181
+ if st.button("Delete Selected"):
182
+ st.session_state.history.pop(int(del_index))
183
+ st.experimental_rerun()
184
+
185
+ if st.button("Download All PDFs (ZIP)"):
186
+ zip_path = download_all()
187
+ if zip_path:
188
+ with open(zip_path, "rb") as f:
189
+ st.download_button("Download ZIP", f, file_name="All_Reports.zip")
190
+ else:
191
+ st.info("No incidents recorded yet.")