Shakir60 commited on
Commit
dbfc49d
·
verified ·
1 Parent(s): 411da4d

Update rag_utils.py

Browse files
Files changed (1) hide show
  1. rag_utils.py +134 -71
rag_utils.py CHANGED
@@ -1,73 +1,136 @@
1
- from langchain.embeddings import HuggingFaceEmbeddings
2
- from langchain.vectorstores import FAISS
3
- from langchain.text_splitter import RecursiveCharacterTextSplitter
4
- import streamlit as st
5
 
6
- class RAGSystem:
7
- def __init__(self):
8
- self.embeddings = HuggingFaceEmbeddings(
9
- model_name="sentence-transformers/all-mpnet-base-v2"
10
- )
11
- self.vector_store = None
12
- self.text_splitter = RecursiveCharacterTextSplitter(
13
- chunk_size=500,
14
- chunk_overlap=50
15
- )
16
-
17
- def initialize_knowledge_base(self, knowledge_base):
18
- """Initialize vector store with construction knowledge"""
19
- documents = []
20
-
21
- for damage_type, cases in knowledge_base.items():
22
- for case in cases:
23
- doc_text = f"""
24
- Damage Type: {damage_type}
25
- Severity: {case['severity']}
26
- Description: {case['description']}
27
- Repair Methods: {', '.join(case['repair_method'])}
28
- Cost: {case['estimated_cost']}
29
- Timeframe: {case['timeframe']}
30
- Location: {case['location']}
31
- Required Expertise: {case['required_expertise']}
32
- Immediate Action: {case['immediate_action']}
33
- Prevention: {case['prevention']}
34
- """
35
- documents.append(doc_text)
36
-
37
- splits = self.text_splitter.create_documents(documents)
38
- self.vector_store = FAISS.from_documents(splits, self.embeddings)
39
-
40
- def query_knowledge_base(self, query, k=3):
41
- """Query the vector store for relevant information"""
42
- if not self.vector_store:
43
- raise ValueError("Vector store not initialized")
44
-
45
- results = self.vector_store.similarity_search(query, k=k)
46
- return results
47
-
48
- def get_enhanced_analysis(self, damage_type, confidence, custom_query=None):
49
- """Get enhanced analysis based on damage type and confidence"""
50
- if not custom_query:
51
- query = f"What are the key considerations and recommendations for {damage_type} with {confidence}% confidence?"
52
- else:
53
- query = custom_query
54
-
55
- relevant_docs = self.query_knowledge_base(query)
56
-
57
- enhanced_info = {
58
- "technical_details": [],
59
- "safety_considerations": [],
60
- "expert_recommendations": []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  }
62
-
63
- for doc in relevant_docs:
64
- content = doc.page_content
65
-
66
- if "severity" in content.lower() or "description" in content.lower():
67
- enhanced_info["technical_details"].append(content)
68
- elif "immediate action" in content.lower() or "prevention" in content.lower():
69
- enhanced_info["safety_considerations"].append(content)
70
- elif "repair" in content.lower() or "expertise" in content.lower():
71
- enhanced_info["expert_recommendations"].append(content)
72
-
73
- return enhanced_info
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # knowledge_base.py
 
 
 
2
 
3
+ import logging
4
+
5
+ # Configure logging
6
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
7
+
8
+ # Knowledge base containing structural damage information
9
+ KNOWLEDGE_BASE = {
10
+ "spalling": [
11
+ {
12
+ "severity": "Critical",
13
+ "description": "Severe concrete spalling with exposed reinforcement and section loss",
14
+ "repair_method": [
15
+ "Install temporary support",
16
+ "Remove deteriorated concrete",
17
+ "Clean and treat reinforcement",
18
+ "Apply corrosion inhibitor",
19
+ "Apply bonding agent",
20
+ "High-strength repair mortar"
21
+ ],
22
+ "estimated_cost": "Very High ($15,000+)",
23
+ "timeframe": "3-4 weeks",
24
+ "location": "Primary structural elements",
25
+ "required_expertise": "Structural Engineer + Specialist Contractor",
26
+ "immediate_action": "Evacuate area, install temporary support, prevent access",
27
+ "prevention": "Regular inspections, waterproofing, chloride protection"
28
+ },
29
+ {
30
+ "severity": "High",
31
+ "description": "Surface spalling with visible reinforcement",
32
+ "repair_method": [
33
+ "Remove damaged concrete",
34
+ "Treat reinforcement",
35
+ "Apply repair mortar",
36
+ "Surface treatment"
37
+ ],
38
+ "estimated_cost": "High ($8,000-$15,000)",
39
+ "timeframe": "2-3 weeks",
40
+ "location": "Structural elements",
41
+ "required_expertise": "Structural Engineer",
42
+ "immediate_action": "Area isolation, temporary support assessment",
43
+ "prevention": "Protective coatings, drainage improvement"
44
+ }
45
+ ],
46
+ "reinforcement_corrosion": [
47
+ {
48
+ "severity": "Critical",
49
+ "description": "Severe corrosion with >30% section loss",
50
+ "repair_method": [
51
+ "Structural support",
52
+ "Remove concrete",
53
+ "Replace reinforcement",
54
+ "Corrosion protection",
55
+ "Concrete repair"
56
+ ],
57
+ "estimated_cost": "Critical ($20,000+)",
58
+ "timeframe": "4-6 weeks",
59
+ "location": "Load-bearing elements",
60
+ "required_expertise": "Senior Structural Engineer",
61
+ "immediate_action": "Immediate evacuation, emergency shoring",
62
+ "prevention": "Waterproofing, cathodic protection"
63
+ }
64
+ ],
65
+ "structural_crack": [
66
+ {
67
+ "severity": "High",
68
+ "description": "Cracks >5mm in structural elements",
69
+ "repair_method": [
70
+ "Structural analysis",
71
+ "Epoxy injection",
72
+ "Carbon fiber reinforcement",
73
+ "Crack monitoring"
74
+ ],
75
+ "estimated_cost": "High ($10,000-$20,000)",
76
+ "timeframe": "2-4 weeks",
77
+ "location": "Primary structure",
78
+ "required_expertise": "Structural Engineer",
79
+ "immediate_action": "Install crack monitors, load restriction",
80
+ "prevention": "Load management, joint maintenance"
81
  }
82
+ ],
83
+ "dampness": [
84
+ {
85
+ "severity": "Medium",
86
+ "description": "Active water penetration with efflorescence",
87
+ "repair_method": [
88
+ "Water source identification",
89
+ "Drainage improvement",
90
+ "Waterproof membrane",
91
+ "Ventilation"
92
+ ],
93
+ "estimated_cost": "Medium ($5,000-$10,000)",
94
+ "timeframe": "1-2 weeks",
95
+ "location": "Various",
96
+ "required_expertise": "Waterproofing Specialist",
97
+ "immediate_action": "Dehumidification, efflorescence cleaning",
98
+ "prevention": "Proper drainage, vapor barriers"
99
+ }
100
+ ],
101
+ "no_damage": [
102
+ {
103
+ "severity": "Low",
104
+ "description": "No significant structural issues",
105
+ "repair_method": [
106
+ "Regular inspection",
107
+ "Preventive maintenance"
108
+ ],
109
+ "estimated_cost": "Low ($500-$2,000)",
110
+ "timeframe": "1-2 days",
111
+ "location": "General",
112
+ "required_expertise": "Building Inspector",
113
+ "immediate_action": "Continue monitoring",
114
+ "prevention": "Regular maintenance schedule"
115
+ }
116
+ ]
117
+ }
118
+
119
+ # Damage type metadata
120
+ DAMAGE_TYPES = {
121
+ 0: {'name': 'spalling', 'risk': 'High', 'color': '#ff4d4d'},
122
+ 1: {'name': 'reinforcement_corrosion', 'risk': 'Critical', 'color': '#800000'},
123
+ 2: {'name': 'structural_crack', 'risk': 'High', 'color': '#ff6b6b'},
124
+ 3: {'name': 'dampness', 'risk': 'Medium', 'color': '#4dabf7'},
125
+ 4: {'name': 'no_damage', 'risk': 'Low', 'color': '#40c057'}
126
+ }
127
+
128
+ # Validation for knowledge base
129
+ required_keys = ['severity', 'description', 'repair_method', 'estimated_cost', 'timeframe', 'location', 'required_expertise', 'immediate_action', 'prevention']
130
+ for damage_type, cases in KNOWLEDGE_BASE.items():
131
+ for case in cases:
132
+ for key in required_keys:
133
+ if key not in case:
134
+ logging.error(f"Missing required field '{key}' in {damage_type}")
135
+ raise ValueError(f"Missing required field '{key}' in {damage_type}")
136
+ logging.info("Knowledge base validation passed.")