Shakir60 commited on
Commit
18cc344
·
verified ·
1 Parent(s): 7fa4ec7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +202 -36
app.py CHANGED
@@ -3,19 +3,102 @@ import torch
3
  from PIL import Image
4
  import numpy as np
5
  from transformers import ViTForImageClassification, ViTImageProcessor
 
6
  import matplotlib.pyplot as plt
7
  import logging
 
 
 
 
 
8
 
9
  # Setup logging
10
  logging.basicConfig(level=logging.INFO)
11
  logger = logging.getLogger(__name__)
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  class ImageAnalyzer:
14
  def __init__(self):
15
  self.device = "cuda" if torch.cuda.is_available() else "cpu"
16
  self.defect_classes = ["spalling", "structural_cracks", "surface_deterioration"]
17
 
18
- # Load model and processor
19
  try:
20
  self.model = ViTForImageClassification.from_pretrained(
21
  "google/vit-base-patch16-224",
@@ -49,50 +132,133 @@ class ImageAnalyzer:
49
  logger.error(f"Analysis error: {e}")
50
  return None
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  def main():
53
- st.title("Construction Defect Analyzer")
 
 
 
 
 
 
54
 
55
- # Initialize analyzer
56
  if 'analyzer' not in st.session_state:
57
  st.session_state.analyzer = ImageAnalyzer()
 
 
58
 
59
- # File uploader
60
- st.write("Upload a construction image for analysis")
61
- uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
 
 
 
62
 
63
- if uploaded_file is not None:
64
- try:
65
- # Display confirmation
66
- st.write("Image received. Processing...")
67
-
68
- # Read and display image
69
- image = Image.open(uploaded_file)
70
- st.image(image, caption='Uploaded Image', use_column_width=True)
71
-
72
- # Analyze image
73
- with st.spinner('Analyzing image...'):
74
- results = st.session_state.analyzer.analyze_image(image)
75
 
76
- if results:
77
- st.success('Analysis complete!')
 
78
 
79
- # Display results
80
- st.subheader("Defect Probabilities")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
- # Create bar chart
83
- fig, ax = plt.subplots()
84
- defects = list(results.keys())
85
- probs = list(results.values())
86
- ax.barh(defects, probs)
87
- ax.set_xlim(0, 1)
88
- plt.tight_layout()
89
- st.pyplot(fig)
90
- else:
91
- st.error("Analysis failed. Please try again.")
92
-
93
- except Exception as e:
94
- st.error(f"Error: {str(e)}")
95
- logger.error(f"Process error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
  if __name__ == "__main__":
98
  main()
 
3
  from PIL import Image
4
  import numpy as np
5
  from transformers import ViTForImageClassification, ViTImageProcessor
6
+ from sentence_transformers import SentenceTransformer
7
  import matplotlib.pyplot as plt
8
  import logging
9
+ import faiss
10
+ from typing import List, Dict
11
+ from datetime import datetime
12
+ from groq import Groq
13
+ import os
14
 
15
  # Setup logging
16
  logging.basicConfig(level=logging.INFO)
17
  logger = logging.getLogger(__name__)
18
 
19
+ class RAGSystem:
20
+ def __init__(self):
21
+ self.embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
22
+ self.knowledge_base = self.load_knowledge_base()
23
+ self.vector_store = self.create_vector_store()
24
+ self.query_history = []
25
+
26
+ def load_knowledge_base(self) -> List[Dict]:
27
+ """Load and preprocess knowledge base"""
28
+ kb = {
29
+ "spalling": [
30
+ {
31
+ "severity": "Critical",
32
+ "description": "Severe concrete spalling with exposed reinforcement",
33
+ "repair_method": "Remove deteriorated concrete, clean reinforcement",
34
+ "estimated_cost": "Very High ($15,000+)",
35
+ "immediate_action": "Evacuate area, install support",
36
+ "prevention": "Regular inspections, waterproofing"
37
+ }
38
+ ],
39
+ "structural_cracks": [
40
+ {
41
+ "severity": "High",
42
+ "description": "Active structural cracks >5mm width",
43
+ "repair_method": "Structural analysis, epoxy injection",
44
+ "estimated_cost": "High ($10,000-$20,000)",
45
+ "immediate_action": "Install crack monitors",
46
+ "prevention": "Regular monitoring, load management"
47
+ }
48
+ ],
49
+ "surface_deterioration": [
50
+ {
51
+ "severity": "Medium",
52
+ "description": "Surface scaling and deterioration",
53
+ "repair_method": "Surface preparation, patch repair",
54
+ "estimated_cost": "Medium ($5,000-$10,000)",
55
+ "immediate_action": "Document extent, plan repairs",
56
+ "prevention": "Surface sealers, proper drainage"
57
+ }
58
+ ]
59
+ }
60
+
61
+ documents = []
62
+ for category, items in kb.items():
63
+ for item in items:
64
+ doc_text = f"Category: {category}\n"
65
+ for key, value in item.items():
66
+ doc_text += f"{key}: {value}\n"
67
+ documents.append({"text": doc_text, "metadata": {"category": category}})
68
+
69
+ return documents
70
+
71
+ def create_vector_store(self):
72
+ """Create FAISS vector store"""
73
+ texts = [doc["text"] for doc in self.knowledge_base]
74
+ embeddings = self.embedding_model.encode(texts)
75
+ dimension = embeddings.shape[1]
76
+ index = faiss.IndexFlatL2(dimension)
77
+ index.add(np.array(embeddings).astype('float32'))
78
+ return index
79
+
80
+ def get_relevant_context(self, query: str, k: int = 2) -> str:
81
+ """Retrieve relevant context based on query"""
82
+ try:
83
+ query_embedding = self.embedding_model.encode([query])
84
+ D, I = self.vector_store.search(np.array(query_embedding).astype('float32'), k)
85
+ context = "\n\n".join([self.knowledge_base[i]["text"] for i in I[0]])
86
+
87
+ self.query_history.append({
88
+ "timestamp": datetime.now().isoformat(),
89
+ "query": query
90
+ })
91
+
92
+ return context
93
+ except Exception as e:
94
+ logger.error(f"Error retrieving context: {e}")
95
+ return ""
96
+
97
  class ImageAnalyzer:
98
  def __init__(self):
99
  self.device = "cuda" if torch.cuda.is_available() else "cpu"
100
  self.defect_classes = ["spalling", "structural_cracks", "surface_deterioration"]
101
 
 
102
  try:
103
  self.model = ViTForImageClassification.from_pretrained(
104
  "google/vit-base-patch16-224",
 
132
  logger.error(f"Analysis error: {e}")
133
  return None
134
 
135
+ def get_groq_response(query: str, context: str) -> str:
136
+ """Get response from Groq LLM"""
137
+ try:
138
+ client = Groq(api_key=os.getenv("GROQ_API_KEY"))
139
+
140
+ prompt = f"""Based on the following context about construction defects, answer the question.
141
+ Context: {context}
142
+ Question: {query}
143
+ Provide a detailed answer based on the given context."""
144
+
145
+ response = client.chat.completions.create(
146
+ messages=[
147
+ {
148
+ "role": "system",
149
+ "content": "You are a construction defect analysis expert."
150
+ },
151
+ {
152
+ "role": "user",
153
+ "content": prompt
154
+ }
155
+ ],
156
+ model="llama2-70b-4096",
157
+ temperature=0.7,
158
+ )
159
+ return response.choices[0].message.content
160
+ except Exception as e:
161
+ logger.error(f"Groq API error: {e}")
162
+ return f"Error: Unable to get response from AI model. Please check your API key and try again."
163
+
164
  def main():
165
+ st.set_page_config(
166
+ page_title="Construction Defect Analyzer",
167
+ page_icon="🏗️",
168
+ layout="wide"
169
+ )
170
+
171
+ st.title("🏗️ Construction Defect Analyzer")
172
 
173
+ # Initialize systems
174
  if 'analyzer' not in st.session_state:
175
  st.session_state.analyzer = ImageAnalyzer()
176
+ if 'rag_system' not in st.session_state:
177
+ st.session_state.rag_system = RAGSystem()
178
 
179
+ # Create two columns
180
+ col1, col2 = st.columns([1, 1])
181
+
182
+ with col1:
183
+ st.subheader("Image Analysis")
184
+ uploaded_file = st.file_uploader("Upload a construction image for analysis", type=["jpg", "jpeg", "png"])
185
 
186
+ if uploaded_file is not None:
187
+ try:
188
+ # Read and display image
189
+ image = Image.open(uploaded_file)
190
+ st.image(image, caption='Uploaded Image', use_column_width=True)
 
 
 
 
 
 
 
191
 
192
+ # Analyze image
193
+ with st.spinner('Analyzing image...'):
194
+ results = st.session_state.analyzer.analyze_image(image)
195
 
196
+ if results:
197
+ st.success('Analysis complete!')
198
+
199
+ # Display results
200
+ st.subheader("Detected Defects")
201
+
202
+ # Create bar chart
203
+ fig, ax = plt.subplots(figsize=(8, 4))
204
+ defects = list(results.keys())
205
+ probs = list(results.values())
206
+ ax.barh(defects, probs)
207
+ ax.set_xlim(0, 1)
208
+ plt.tight_layout()
209
+ st.pyplot(fig)
210
+
211
+ # Get most likely defect
212
+ most_likely_defect = max(results.items(), key=lambda x: x[1])[0]
213
+ st.info(f"Most likely defect: {most_likely_defect}")
214
+ else:
215
+ st.error("Analysis failed. Please try again.")
216
 
217
+ except Exception as e:
218
+ st.error(f"Error: {str(e)}")
219
+ logger.error(f"Process error: {e}")
220
+
221
+ with col2:
222
+ st.subheader("Ask About Defects")
223
+ user_query = st.text_input(
224
+ "Ask a question about the defects or repairs:",
225
+ help="Example: What are the repair methods for spalling?"
226
+ )
227
+
228
+ if user_query:
229
+ with st.spinner('Getting answer...'):
230
+ # Get context from RAG system
231
+ context = st.session_state.rag_system.get_relevant_context(user_query)
232
+
233
+ # Get response from Groq
234
+ response = get_groq_response(user_query, context)
235
+
236
+ # Display response
237
+ st.write("Answer:")
238
+ st.write(response)
239
+
240
+ # Option to view context
241
+ with st.expander("View retrieved information"):
242
+ st.text(context)
243
+
244
+ # Sidebar for information
245
+ with st.sidebar:
246
+ st.header("About")
247
+ st.write("""
248
+ This tool helps analyze construction defects in images and provides
249
+ information about repair methods and best practices.
250
+
251
+ Features:
252
+ - Image analysis for defect detection
253
+ - Information lookup for repair methods
254
+ - Expert AI responses to your questions
255
+ """)
256
+
257
+ # Display API status
258
+ if os.getenv("GROQ_API_KEY"):
259
+ st.success("Groq API: Connected")
260
+ else:
261
+ st.error("Groq API: Not configured")
262
 
263
  if __name__ == "__main__":
264
  main()