Ankitkumarunajaima commited on
Commit
b123e73
Β·
verified Β·
1 Parent(s): 8ffc258

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +234 -0
app.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import cv2
3
+ import numpy as np
4
+ from groq import Groq
5
+ from fpdf import FPDF
6
+ from datetime import datetime
7
+ import sqlite3
8
+ import pandas as pd
9
+ import plotly.graph_objects as go
10
+ import io
11
+ import os
12
+ import gc
13
+
14
+ # --- 1. SETUP & THEME (v58 Base) ---
15
+ st.set_page_config(page_title="Structural AI Audit Pro v59", layout="wide")
16
+
17
+ st.markdown("""
18
+ <style>
19
+ .stApp {
20
+ background-image: linear-gradient(rgba(255, 255, 255, 0.85), rgba(255, 255, 255, 0.85)),
21
+ url('https://img.freepik.com/free-vector/abstract-architectural-blueprint-background_52683-59424.jpg') !important;
22
+ background-size: cover !important;
23
+ background-attachment: fixed !important;
24
+ }
25
+ h1 { color: #1E3A8A !important; font-weight: 800 !important; text-align: center; }
26
+ </style>
27
+ """, unsafe_allow_html=True)
28
+
29
+ st.title("πŸ—οΈ Structural Audit AI Portal v59")
30
+
31
+ # Database Setup
32
+ conn = sqlite3.connect('structural_master_v59.db', check_same_thread=False)
33
+ c = conn.cursor()
34
+ c.execute('''CREATE TABLE IF NOT EXISTS audit_logs
35
+ (date TEXT, time TEXT, location TEXT, material TEXT, width TEXT, depth TEXT, priority TEXT, cost TEXT, details TEXT)''')
36
+ conn.commit()
37
+
38
+ GROQ_API_KEY = "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"
39
+ client = Groq(api_key=GROQ_API_KEY)
40
+
41
+ # --- 2. SIDEBAR (v58 Same) ---
42
+ with st.sidebar:
43
+ st.header("πŸ›‘οΈ Engineering Panel")
44
+ if st.button("πŸ”„ Clear System Cache", use_container_width=True):
45
+ st.cache_data.clear()
46
+ st.cache_resource.clear()
47
+ st.rerun()
48
+
49
+ with st.expander("πŸ“š IS Code Reference", expanded=True):
50
+ st.write("**IS 456:2000 Standards**")
51
+ st.write("β€’ Max Width: 0.3mm\nβ€’ Repair: Grouting > 0.5mm")
52
+ st.divider()
53
+ custom_rate = st.number_input("Base Rate per mmΒ² (Rs.)", value=10.0)
54
+ base_visit_fee = st.number_input("Base Visiting Fee (Rs.)", value=200)
55
+ calib = st.slider("Calibration", 0.01, 0.10, 0.05)
56
+ sens = st.slider("Precision", 0.05, 1.0, 0.30)
57
+
58
+ # --- 3. CORE LOGIC (With Visual 3D Depth) ---
59
+ def process_analysis(img, sensitivity, calib):
60
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
61
+ blur = cv2.GaussianBlur(gray, (7, 7), 0)
62
+ edges = cv2.Canny(blur, int(sensitivity * 30), 100)
63
+ contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
64
+ marked_img = img.copy()
65
+ h_data = np.zeros(img.shape[:2], dtype=np.uint8)
66
+ max_w_px = 0.0; total_len_px = 0.0; total_area_px = 0.0
67
+
68
+ crack_pixels = []
69
+ for cnt in contours:
70
+ x, y, wb, hb = cv2.boundingRect(cnt)
71
+ if wb > 1.5 or hb > 1.5:
72
+ w_px = min(wb, hb); l_px = max(wb, hb)
73
+ if w_px > max_w_px: max_w_px = w_px
74
+ total_len_px += l_px; total_area_px += cv2.contourArea(cnt)
75
+ cv2.drawContours(marked_img, [cnt], -1, (0, 0, 255), 2)
76
+ cv2.drawContours(h_data, [cnt], -1, (255), -1)
77
+
78
+ mask = np.zeros(gray.shape, np.uint8)
79
+ cv2.drawContours(mask, [cnt], -1, 255, -1)
80
+ pixel_values = gray[mask == 255]
81
+ crack_pixels.extend(pixel_values)
82
+
83
+ heatmap = cv2.applyColorMap(cv2.GaussianBlur(h_data, (51, 51), 0), cv2.COLORMAP_JET)
84
+ mm_w = round(max_w_px * calib, 2)
85
+ mm_l = round(total_len_px * calib, 2)
86
+ mm_area = round(total_area_px * (calib ** 2), 2)
87
+
88
+ # 3D Depth Estimation logic (from v57/v58)
89
+ estimated_depth = 0.0
90
+ if crack_pixels and mm_w > 0:
91
+ avg_crack = np.mean(crack_pixels)
92
+ avg_bg = np.mean(gray)
93
+ contrast = (avg_bg - avg_crack) / (avg_bg + 1)
94
+ estimated_depth = round(mm_w * (0.8 + contrast), 2)
95
+ else:
96
+ estimated_depth = round(mm_w * 0.6, 2)
97
+
98
+ # Clamp depth to a reasonable range
99
+ if estimated_depth < 0.1: estimated_depth = 0.1
100
+ if estimated_depth > 100: estimated_depth = 100
101
+
102
+ # --- Visual 3D Depth Effect on Marked Image ---
103
+ # Intensify blue color based on depth, simulate shadow
104
+ if mm_w > 0 and estimated_depth > 0:
105
+ depth_norm = min(estimated_depth / 50.0, 1.0) # Normalize depth for intensity (max 50mm for effect)
106
+ # Create a darker, thicker blue line for deeper cracks
107
+ for cnt in contours:
108
+ cv2.drawContours(marked_img, [cnt], -1, (int(255 * depth_norm), 0, 255), int(2 + depth_norm * 3)) # Bolder blue
109
+ # Add a slight shadow effect (darker outline)
110
+ cv2.drawContours(marked_img, [cnt], -1, (int(100 * depth_norm), 0, int(100 * depth_norm)), int(1 + depth_norm * 1), lineType=cv2.LINE_AA)
111
+
112
+ return marked_img, heatmap, mm_w, mm_l, mm_area, estimated_depth
113
+
114
+ def generate_stress_curve(mm_w, material, location):
115
+ E_base = 35000 if material == "Concrete" else 5000
116
+ loc_factor = {"Column": 1.5, "Beam": 1.3, "Slab": 1.0, "Wall": 0.8}.get(location, 0.6) # Enhanced loc_factor
117
+ E = E_base * loc_factor
118
+
119
+ # Failure strain depends on width and material (Concrete fails earlier for same strain)
120
+ if material == "Concrete":
121
+ failure_strain = 0.002 + (mm_w / 60)
122
+ else: # Plaster can deform more before 'failure' in terms of structural load
123
+ failure_strain = 0.004 + (mm_w / 50)
124
+
125
+ strain = np.linspace(0, failure_strain * 1.5, 100)
126
+
127
+ # Stress-Strain Parabolic Curve (IS 456 for concrete, adjusted for plaster)
128
+ stress = np.maximum(E * strain * (1 - (strain / (2.2 * failure_strain))), 0) # Adjusted constant for better curve shape
129
+
130
+ fig = go.Figure()
131
+ fig.add_trace(go.Scatter(x=strain, y=stress, mode='lines', name='Structural Integrity', line=dict(color='#ff5733', width=3)))
132
+
133
+ # Calculate failure point (max stress)
134
+ max_stress_idx = np.argmax(stress)
135
+ fig.add_trace(go.Scatter(x=[strain[max_stress_idx]], y=[stress[max_stress_idx]],
136
+ mode='markers', name='Failure Point',
137
+ marker=dict(color='red', size=10, symbol='x', line=dict(width=2, color='DarkRed')))) # Clearer X mark
138
+
139
+ fig.update_layout(title=f"Physics Plot: {location} ({material})",
140
+ xaxis_title="Strain (Ξ΅)", yaxis_title="Stress (MPa)",
141
+ template="plotly_dark", height=280)
142
+ return fig
143
+
144
+ def get_priority_v54(width, depth, material):
145
+ # Priority logic now more sensitive to depth
146
+ if material == "Plaster":
147
+ if width < 1.0 and depth < 5.0: return "LOW", "🟒", "Safe (Surface Plaster Crack)"
148
+ elif (1.0 <= width < 3.0 and depth < 10.0) or (depth >= 5.0 and depth < 15.0): return "MEDIUM", "🟑", "Warning"
149
+ else: return "HIGH", "πŸ”΄", "Deep Crack (Internal Check Req.)"
150
+ else: # Concrete
151
+ if width < 0.3 and depth < 10.0: return "LOW", "🟒", "Safe (Hairline)"
152
+ elif (0.3 <= width < 0.7 and depth < 20.0) or (depth >= 10.0 and depth < 30.0): return "MEDIUM", "🟑", "Warning (Structural)"
153
+ else: return "HIGH", "πŸ”΄", "CRITICAL (Immediate Action!)"
154
+
155
+ # --- 4. TABS UI ---
156
+ tab1, tab2, tab3 = st.tabs(["πŸš€ Batch Audit", "πŸ“Έ Live Cam", "πŸ“œ History"])
157
+
158
+ with tab1:
159
+ files = st.file_uploader("Upload Crack Images", accept_multiple_files=True, key="file_uploader_v59")
160
+ if files:
161
+ c1, c2 = st.columns(2)
162
+ with c1: mat = st.radio("Material:", ["Concrete", "Plaster"], horizontal=True)
163
+ with c2: loc = st.selectbox("Location:", ["Wall", "Column", "Beam", "Slab", "Surface"])
164
+
165
+ if st.button("Execute Batch Analysis", use_container_width=True):
166
+ gc.collect()
167
+ pdf = FPDF()
168
+ pdf.set_font("Arial", size=10) # Set default font
169
+
170
+ for i, f in enumerate(files):
171
+ img = cv2.imdecode(np.frombuffer(f.read(), np.uint8), 1)
172
+ m_img, h_img, w, l, area, depth = process_analysis(img, sens, calib)
173
+ priority, emoji, p_text = get_priority_v54(w, depth, mat)
174
+
175
+ total_repair = round((area * custom_rate * (1.5 if priority=="MEDIUM" else 2.5 if priority=="HIGH" else 1.0)) + base_visit_fee, 2)
176
+
177
+ # UI Preview
178
+ st.subheader(f"Result {i+1}: {f.name} ({emoji} {p_text})")
179
+ m1, m2, m3, m4 = st.columns(4)
180
+ m1.metric("Width", f"{w} mm")
181
+ m2.metric("Depth", f"{depth} mm")
182
+ m3.metric("Status", p_text)
183
+ m4.metric("Estimate", f"Rs. {total_repair}")
184
+
185
+ # Image Layout Fix: Use columns to display images side-by-side
186
+ img_col1, img_col2, img_col3 = st.columns(3)
187
+ with img_col1: st.image(img, caption="Original", use_column_width=True)
188
+ with img_col2: st.image(m_img, caption="Marked (3D Depth)", use_column_width=True) # Updated caption
189
+ with img_col3: st.image(h_img, caption="Thermal Heatmap", use_column_width=True)
190
+
191
+ graph_key = f"graph_{datetime.now().strftime('%Y%m%d%H%M%S%f')}_{i}"
192
+ fig = generate_stress_curve(w, mat, loc)
193
+ st.plotly_chart(fig, use_container_width=True, key=graph_key)
194
+
195
+ prompt = f"Analyze {w}mm width and {depth}mm depth crack on {loc} ({mat}). Priority: {priority}. Give detailed Cause & Repair solutions."
196
+ ai_resp = client.chat.completions.create(messages=[{"role":"user","content":prompt}], model="llama-3.1-8b-instant").choices[0].message.content
197
+ st.info(ai_resp)
198
+
199
+ # Database (v58 Same)
200
+ c.execute("INSERT INTO audit_logs VALUES (?,?,?,?,?,?,?,?,?)",
201
+ (datetime.now().strftime('%Y-%m-%d'), datetime.now().strftime('%H:%M:%S'), loc, mat, f"{w}mm", f"{depth}mm", priority, f"Rs. {total_repair}", ai_resp))
202
+ conn.commit()
203
+
204
+ # PDF Export (v58 Same)
205
+ pdf.add_page()
206
+ pdf.set_font("Arial", 'B', 14)
207
+ pdf.cell(0, 10, f"STRUCTURAL REPORT - {f.name}", 1, 1, 'C')
208
+ pdf.set_font("Arial", size=10)
209
+ pdf.cell(0, 8, f"Location: {loc} | Material: {mat} | Width: {w}mm | Depth: {depth}mm", ln=1)
210
+ pdf.cell(0, 8, f"Priority: {priority} | Estimate: Rs. {total_repair}", ln=1)
211
+
212
+ o_p, m_p, h_p, g_p = f"o_{i}.jpg", f"m_{i}.jpg", f"h_{i}.jpg", f"g_{i}.png"
213
+ cv2.imwrite(o_p, img); cv2.imwrite(m_p, m_img); cv2.imwrite(h_p, h_img); fig.write_image(g_p)
214
+
215
+ pdf.image(o_p, 10, 40, 90, 60); pdf.image(m_p, 105, 40, 90, 60)
216
+ pdf.image(h_p, 10, 105, 90, 60); pdf.image(g_p, 105, 105, 90, 60)
217
+
218
+ pdf.add_page()
219
+ pdf.set_font("Arial", size=10)
220
+ pdf.multi_cell(0, 6, txt=ai_resp.encode('latin-1', 'ignore').decode('latin-1'))
221
+
222
+ st.download_button("πŸ“₯ Download PDF Report", bytes(pdf.output(dest='S')), "Audit_Report.pdf", use_container_width=True)
223
+
224
+ with tab2: # Live Cam (v58 with depth info)
225
+ live = st.camera_input("Scan Crack")
226
+ if live:
227
+ img_l = cv2.imdecode(np.frombuffer(live.read(), np.uint8), 1)
228
+ m_l, _, w_l, _, _, d_l = process_analysis(img_l, sens, calib)
229
+ st.image(m_l, caption=f"Detected: {w_l}mm | Depth: {d_l}mm", use_column_width=True)
230
+
231
+ with tab3: # History (v58 Same)
232
+ history = pd.read_sql_query("SELECT * FROM audit_logs ORDER BY date DESC", conn)
233
+ st.dataframe(history, use_container_width=True)
234
+