Update app.py
Browse files
app.py
CHANGED
|
@@ -1,152 +1,67 @@
|
|
| 1 |
-
import
|
| 2 |
import torch
|
| 3 |
-
from transformers import
|
| 4 |
-
from
|
| 5 |
-
import
|
| 6 |
-
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 7 |
-
from langchain_community.llms import HuggingFaceHub
|
| 8 |
-
from langchain_community.vectorstores import FAISS
|
| 9 |
-
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 10 |
-
from langchain.docstore.document import Document
|
| 11 |
-
from langchain.prompts import PromptTemplate
|
| 12 |
-
from langchain.chains import RetrievalQA
|
| 13 |
-
import os
|
| 14 |
|
| 15 |
-
|
| 16 |
-
st.set_page_config(
|
| 17 |
-
page_title="Building Damage Analysis",
|
| 18 |
-
page_icon="🏗️",
|
| 19 |
-
layout="wide"
|
| 20 |
-
)
|
| 21 |
|
| 22 |
-
#
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
from huggingface_hub import login
|
| 27 |
-
login(token="HUGGINGFACE_API_TOKEN")
|
| 28 |
-
damage_model = ViTForImageClassification.from_pretrained(
|
| 29 |
-
"microsoft/vit-base-patch16-224",
|
| 30 |
-
use_auth_token=True
|
| 31 |
-
)
|
| 32 |
-
processor = ViTImageProcessor.from_pretrained("microsoft/vit-base-patch16-224")
|
| 33 |
-
|
| 34 |
-
# Text model
|
| 35 |
-
llm = HuggingFaceHub(
|
| 36 |
-
repo_id="google/flan-t5-large",
|
| 37 |
-
model_kwargs={"temperature": 0.7, "max_length": 512}
|
| 38 |
-
)
|
| 39 |
-
|
| 40 |
-
embeddings = HuggingFaceEmbeddings(
|
| 41 |
-
model_name='sentence-transformers/all-MiniLM-L6-v2'
|
| 42 |
-
)
|
| 43 |
-
|
| 44 |
-
return damage_model, processor, embeddings, llm
|
| 45 |
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
},
|
| 53 |
-
{
|
| 54 |
-
"repair_description": "Concrete beam damage with exposed rebar. Requires immediate attention.",
|
| 55 |
-
"repair_cost": 7500,
|
| 56 |
-
"damage_type": "Beam Damage"
|
| 57 |
-
},
|
| 58 |
-
{
|
| 59 |
-
"repair_description": "Foundation settling causing structural issues. Need underpinning.",
|
| 60 |
-
"repair_cost": 15000,
|
| 61 |
-
"damage_type": "Foundation Issue"
|
| 62 |
-
}
|
| 63 |
-
]
|
| 64 |
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
Document(
|
| 69 |
-
page_content=f"{item['repair_description']} Cost: ${item['repair_cost']}",
|
| 70 |
-
metadata={'cost': item['repair_cost'], 'damage_type': item['damage_type']}
|
| 71 |
-
)
|
| 72 |
-
for item in SAMPLE_DATA
|
| 73 |
-
]
|
| 74 |
-
|
| 75 |
-
# Create vector store
|
| 76 |
-
vectorstore = FAISS.from_documents(documents, embeddings)
|
| 77 |
-
|
| 78 |
-
# Create prompt template
|
| 79 |
-
template = """
|
| 80 |
-
Analyze building damage and provide repair recommendations based on this context:
|
| 81 |
-
{context}
|
| 82 |
-
|
| 83 |
-
For damage type: {question}
|
| 84 |
-
|
| 85 |
-
Provide:
|
| 86 |
-
1. Damage assessment
|
| 87 |
-
2. Repair steps
|
| 88 |
-
3. Safety considerations
|
| 89 |
-
4. Estimated cost range
|
| 90 |
-
"""
|
| 91 |
-
|
| 92 |
-
prompt = PromptTemplate(template=template, input_variables=["context", "question"])
|
| 93 |
-
|
| 94 |
-
# Create QA chain
|
| 95 |
-
qa_chain = RetrievalQA.from_chain_type(
|
| 96 |
-
llm=llm,
|
| 97 |
-
chain_type="stuff",
|
| 98 |
-
retriever=vectorstore.as_retriever(search_kwargs={'k': 2}),
|
| 99 |
-
chain_type_kwargs={"prompt": prompt}
|
| 100 |
-
)
|
| 101 |
-
|
| 102 |
-
return qa_chain
|
| 103 |
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
inputs = processor(images=image, return_tensors="pt")
|
| 106 |
-
outputs =
|
| 107 |
-
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
-
|
| 111 |
-
st.title("🏗️ Building Damage Detection & Analysis")
|
| 112 |
-
st.markdown("""
|
| 113 |
-
Upload a photo of building damage for AI analysis and repair recommendations.
|
| 114 |
-
""")
|
| 115 |
-
|
| 116 |
-
# Load models on first run
|
| 117 |
-
if 'models_loaded' not in st.session_state:
|
| 118 |
-
with st.spinner('Loading AI models...'):
|
| 119 |
-
damage_model, processor, embeddings, llm = load_models()
|
| 120 |
-
qa_chain = setup_rag(embeddings, llm)
|
| 121 |
-
st.session_state['models_loaded'] = True
|
| 122 |
-
st.session_state['models'] = (damage_model, processor, qa_chain)
|
| 123 |
-
|
| 124 |
-
damage_model, processor, qa_chain = st.session_state['models']
|
| 125 |
-
|
| 126 |
-
# File upload
|
| 127 |
-
uploaded_file = st.file_uploader("Upload building damage photo", type=["jpg", "jpeg", "png"])
|
| 128 |
-
|
| 129 |
-
if uploaded_file:
|
| 130 |
-
# Display image
|
| 131 |
-
image = Image.open(uploaded_file)
|
| 132 |
-
st.image(image, caption="Uploaded Image", use_column_width=True)
|
| 133 |
-
|
| 134 |
-
with st.spinner('Analyzing damage...'):
|
| 135 |
-
# Process image
|
| 136 |
-
predictions = process_image(image, damage_model, processor)
|
| 137 |
-
damage_types = ["Wall Crack", "Beam Damage", "Foundation Issue",
|
| 138 |
-
"Roof Damage", "Structural Damage"]
|
| 139 |
-
|
| 140 |
-
# Show results
|
| 141 |
-
st.subheader("Detected Damage Types")
|
| 142 |
-
for damage_type, prob in zip(damage_types, predictions):
|
| 143 |
-
if prob > 0.2:
|
| 144 |
-
st.metric(damage_type, f"{prob:.1%}")
|
| 145 |
-
|
| 146 |
-
with st.spinner(f'Generating analysis for {damage_type}...'):
|
| 147 |
-
analysis = qa_chain.invoke(damage_type)
|
| 148 |
-
st.markdown(f"### Analysis for {damage_type}")
|
| 149 |
-
st.markdown(analysis['result'])
|
| 150 |
|
| 151 |
-
if __name__ ==
|
| 152 |
-
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
import torch
|
| 3 |
+
from transformers import AutoProcessor, AutoModelForImageClassification
|
| 4 |
+
from sentence_transformers import SentenceTransformer
|
| 5 |
+
import sqlite3
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
+
app = Flask(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
# Load the defect detection model (open-source, hugging face model)
|
| 10 |
+
DETECTION_MODEL_NAME = "microsoft/beit-base-patch16-224-pt22k-ft22k"
|
| 11 |
+
processor = AutoProcessor.from_pretrained(DETECTION_MODEL_NAME)
|
| 12 |
+
detection_model = AutoModelForImageClassification.from_pretrained(DETECTION_MODEL_NAME)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
defects_to_remedies = {
|
| 15 |
+
"crack": "Fill cracks with epoxy. Structural cracks might need professional inspection.",
|
| 16 |
+
"spalling": "Clean affected area and apply anti-corrosion primer before repairing.",
|
| 17 |
+
"leakage": "Fix water source, seal with water-proofing compounds.",
|
| 18 |
+
"mold": "Clean the mold, improve ventilation, and apply mold-resistant paint."
|
| 19 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
# Initialize a Sentence Transformer for text embeddings
|
| 22 |
+
EMBEDDING_MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2"
|
| 23 |
+
embedding_model = SentenceTransformer(EMBEDDING_MODEL_NAME)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
# SQLite database setup
|
| 26 |
+
db_conn = sqlite3.connect('defects.db', check_same_thread=False)
|
| 27 |
+
c = db_conn.cursor()
|
| 28 |
+
c.execute('''CREATE TABLE IF NOT EXISTS defects (id INTEGER PRIMARY KEY, defect TEXT, remedy TEXT, embedding BLOB)''')
|
| 29 |
+
db_conn.commit()
|
| 30 |
+
|
| 31 |
+
# Populate defect remedies table if empty
|
| 32 |
+
def seed_database():
|
| 33 |
+
for defect, remedy in defects_to_remedies.items():
|
| 34 |
+
c.execute("SELECT * FROM defects WHERE defect=?", (defect,))
|
| 35 |
+
if not c.fetchone():
|
| 36 |
+
embedding = embedding_model.encode(remedy).tolist()
|
| 37 |
+
c.execute("INSERT INTO defects (defect, remedy, embedding) VALUES (?, ?, ?)", (defect, remedy, str(embedding)))
|
| 38 |
+
db_conn.commit()
|
| 39 |
+
|
| 40 |
+
seed_database()
|
| 41 |
+
|
| 42 |
+
@app.route('/detect', methods=['POST'])
|
| 43 |
+
def detect_defect():
|
| 44 |
+
if 'image' not in request.files:
|
| 45 |
+
return jsonify({"error": "No image uploaded."}), 400
|
| 46 |
+
|
| 47 |
+
image = request.files['image'].read()
|
| 48 |
+
|
| 49 |
+
# Preprocess and predict the defect
|
| 50 |
inputs = processor(images=image, return_tensors="pt")
|
| 51 |
+
outputs = detection_model(**inputs)
|
| 52 |
+
probs = torch.nn.functional.softmax(outputs.logits, dim=1)
|
| 53 |
+
predicted_class = torch.argmax(probs, dim=1)
|
| 54 |
+
class_name = detection_model.config.id2label[predicted_class.item()]
|
| 55 |
+
|
| 56 |
+
# Query remedy
|
| 57 |
+
c.execute("SELECT remedy FROM defects WHERE defect=?", (class_name,))
|
| 58 |
+
row = c.fetchone()
|
| 59 |
+
if row:
|
| 60 |
+
remedy = row[0]
|
| 61 |
+
else:
|
| 62 |
+
remedy = "No specific remedy available for this defect."
|
| 63 |
|
| 64 |
+
return jsonify({"detected_defect": class_name, "remedy": remedy})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
+
if __name__ == '__main__':
|
| 67 |
+
app.run(debug=True)
|