Shakir60 commited on
Commit
9814e5f
·
verified ·
1 Parent(s): eee8b01

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -80
app.py CHANGED
@@ -1,90 +1,59 @@
1
  import streamlit as st
2
- import torch
3
- from transformers import ViTForImageClassification, ViTImageProcessor
4
  from PIL import Image
 
5
  import numpy as np
6
- from langchain.vectorstores import FAISS
7
- from langchain.embeddings import HuggingFaceEmbeddings
8
- from langchain.document_loaders import TextLoader
9
- from langchain.text_splitter import CharacterTextSplitter
10
- import io
11
- import json
12
 
13
- # Load pre-trained model and processor
14
- model_name = "google/vit-base-patch16-224-in21k"
15
- processor = ViTImageProcessor.from_pretrained(model_name)
16
- model = ViTForImageClassification.from_pretrained(model_name)
17
 
18
- # Custom class labels
19
- damage_types = [
20
- "spalling",
21
- "reinforcement_corrosion",
22
- "flexural_crack",
23
- "structural_crack",
24
- "dampness",
25
- "impact_failure"
26
- ]
27
 
28
- # Initialize FAISS vector store
29
- embeddings = HuggingFaceEmbeddings()
30
- knowledge_base = FAISS.load_local("knowledge_base", embeddings)
31
 
32
- def process_image(image):
33
- # Preprocess image
34
- inputs = processor(images=image, return_tensors="pt")
35
 
36
- # Get model predictions
37
- outputs = model(**inputs)
38
- probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
39
 
40
- # Get top predictions
41
- top_probs, top_indices = torch.topk(probs, len(damage_types))
42
-
43
- return {
44
- damage_types[idx]: float(prob)
45
- for idx, prob in zip(top_indices[0], top_probs[0])
46
- }
47
-
48
- def get_recommendations(damage_type):
49
- # Query vector store for recommendations
50
- docs = knowledge_base.similarity_search(
51
- f"Remedial measures for {damage_type} in building structures",
52
- k=3
53
- )
54
- return [doc.page_content for doc in docs]
55
-
56
- # Streamlit UI
57
- st.title("Structural Damage Assessment Tool")
58
-
59
- # File upload
60
- uploaded_file = st.file_uploader("Upload structural image", type=["jpg", "jpeg", "png"])
61
-
62
- if uploaded_file:
63
- # Display image
64
- image = Image.open(uploaded_file)
65
- st.image(image, caption="Uploaded Image", use_column_width=True)
66
-
67
- # Process image
68
- with st.spinner("Analyzing image..."):
69
- predictions = process_image(image)
70
-
71
- # Display results
72
- st.subheader("Damage Assessment")
73
- for damage_type, probability in predictions.items():
74
- st.progress(probability)
75
- st.write(f"{damage_type.replace('_', ' ').title()}: {probability:.2%}")
76
 
77
- # Show recommendations
78
- if probability > 0.5:
79
- st.subheader(f"Recommendations for {damage_type.replace('_', ' ').title()}")
80
- recommendations = get_recommendations(damage_type)
81
- for i, rec in enumerate(recommendations, 1):
82
- st.write(f"{i}. {rec}")
83
-
84
- # Generate report
85
- st.download_button(
86
- "Download Report",
87
- json.dumps(predictions, indent=2),
88
- "assessment_report.json",
89
- "application/json"
90
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ from transformers import pipeline
 
3
  from PIL import Image
4
+ import torch
5
  import numpy as np
 
 
 
 
 
 
6
 
7
+ # Initialize classifier
8
+ classifier = pipeline("image-classification", model="microsoft/resnet-50")
 
 
9
 
10
+ # Page config
11
+ st.set_page_config(page_title="Structural Damage Assessment", layout="wide")
 
 
 
 
 
 
 
12
 
13
+ def analyze_damage(image):
14
+ predictions = classifier(image)
15
+ return predictions
16
 
17
+ def main():
18
+ st.title("Structural Damage Assessment Tool")
 
19
 
20
+ # Sidebar
21
+ st.sidebar.header("Upload Options")
22
+ uploaded_file = st.sidebar.file_uploader("Choose an image", type=['png', 'jpg', 'jpeg'])
23
 
24
+ if uploaded_file:
25
+ # Display image
26
+ image = Image.open(uploaded_file)
27
+ col1, col2 = st.columns(2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
+ with col1:
30
+ st.image(image, caption="Uploaded Structure", use_column_width=True)
31
+
32
+ # Analyze image
33
+ with col2:
34
+ st.header("Analysis Results")
35
+ with st.spinner("Analyzing..."):
36
+ results = analyze_damage(image)
37
+
38
+ for result in results:
39
+ score = result['score'] * 100
40
+ st.progress(int(score))
41
+ st.write(f"{result['label']}: {score:.2f}%")
42
+
43
+ # Recommendations
44
+ st.header("Recommendations")
45
+ damages = {
46
+ 'Spalling': ['Repair exposed areas', 'Apply protective coating'],
47
+ 'Cracks': ['Monitor crack width', 'Apply crack sealant'],
48
+ 'Corrosion': ['Remove rust', 'Apply anti-corrosive treatment'],
49
+ 'Dampness': ['Improve drainage', 'Apply waterproofing']
50
+ }
51
+
52
+ for damage, remedies in damages.items():
53
+ if any(damage.lower() in r['label'].lower() for r in results):
54
+ st.subheader(f"{damage} Remedial Measures:")
55
+ for remedy in remedies:
56
+ st.write(f"- {remedy}")
57
+
58
+ if __name__ == "__main__":
59
+ main()