Update app.py
Browse files
app.py
CHANGED
|
@@ -1,102 +1,246 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
|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import torchvision.models as models
|
| 9 |
+
from PIL import Image
|
| 10 |
+
import gradio as gr
|
| 11 |
+
from groq import Groq
|
| 12 |
+
from reportlab.lib.pagesizes import A4
|
| 13 |
+
from reportlab.pdfgen import canvas
|
| 14 |
+
|
| 15 |
+
# Load API Key
|
| 16 |
+
api_key = os.environ.get("GROQ_API_KEY")
|
| 17 |
+
if not api_key:
|
| 18 |
+
raise ValueError("GROQ_API_KEY not found in environment. Please add it in HF Space Secrets.")
|
| 19 |
+
client = Groq(api_key=api_key)
|
| 20 |
+
|
| 21 |
+
# ------------------------------
|
| 22 |
+
# Model: Soil Classifier
|
| 23 |
+
# ------------------------------
|
| 24 |
+
class SoilClassifier(nn.Module):
|
| 25 |
+
def __init__(self):
|
| 26 |
+
super(SoilClassifier, self).__init__()
|
| 27 |
+
self.base_model = models.resnet18(weights=None)
|
| 28 |
+
num_features = self.base_model.fc.in_features
|
| 29 |
+
self.base_model.fc = nn.Linear(num_features, 1)
|
| 30 |
+
|
| 31 |
+
def forward(self, x):
|
| 32 |
+
return self.base_model(x)
|
| 33 |
+
|
| 34 |
+
model = SoilClassifier()
|
| 35 |
+
model.base_model.load_state_dict(torch.load('soil_model.pth', map_location=torch.device('cpu')))
|
| 36 |
+
model.eval()
|
| 37 |
+
|
| 38 |
+
transform = transforms.Compose([
|
| 39 |
+
transforms.Resize((224, 224)),
|
| 40 |
+
transforms.ToTensor(),
|
| 41 |
+
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
|
| 42 |
+
])
|
| 43 |
+
|
| 44 |
+
# ------------------------------
|
| 45 |
+
# Shared report log
|
| 46 |
+
# ------------------------------
|
| 47 |
+
report_summary = []
|
| 48 |
+
|
| 49 |
+
# ------------------------------
|
| 50 |
+
# Soil Prediction Function
|
| 51 |
+
# ------------------------------
|
| 52 |
+
def predict_soil_type(image):
|
| 53 |
+
image = image.convert("RGB")
|
| 54 |
+
img_tensor = transform(image).unsqueeze(0)
|
| 55 |
+
with torch.no_grad():
|
| 56 |
+
outputs = model(img_tensor)
|
| 57 |
+
raw_output = outputs.item()
|
| 58 |
+
prediction = torch.sigmoid(outputs).item()
|
| 59 |
+
result = f"Model Raw Output: {raw_output:.4f}"
|
| 60 |
+
report_summary.append(f"Soil Image Prediction: {result}")
|
| 61 |
+
return result
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# ------------------------------
|
| 65 |
+
# AI Advisor
|
| 66 |
+
# ------------------------------
|
| 67 |
+
def ask_soil_region(query):
|
| 68 |
+
prompt = f"""You are GeoMate, a world-class geotechnical expert.
|
| 69 |
+
Answer the following query using global soil knowledge, latest construction practices, and foundation design standards.
|
| 70 |
+
Query: {query}"""
|
| 71 |
+
response = client.chat.completions.create(
|
| 72 |
+
model="llama-3.1-8b-instant",
|
| 73 |
+
messages=[{"role": "user", "content": prompt}]
|
| 74 |
+
)
|
| 75 |
+
return response.choices[0].message.content
|
| 76 |
+
|
| 77 |
+
# ------------------------------
|
| 78 |
+
# Classification System
|
| 79 |
+
# ------------------------------
|
| 80 |
+
def classify_soil(system, liquid_limit, plasticity_index, grain_size):
|
| 81 |
+
try:
|
| 82 |
+
result = ""
|
| 83 |
+
if system == "USCS":
|
| 84 |
+
if grain_size > 50:
|
| 85 |
+
result = "Gravel"
|
| 86 |
+
elif grain_size > 0.075:
|
| 87 |
+
result = "Sand"
|
| 88 |
+
else:
|
| 89 |
+
result = "Clay" if plasticity_index > 7 else "Silt"
|
| 90 |
+
elif system == "AASHTO":
|
| 91 |
+
if liquid_limit < 40 and plasticity_index < 10:
|
| 92 |
+
result = "A-1 or A-2 (Granular Soil)"
|
| 93 |
+
elif plasticity_index > 10:
|
| 94 |
+
result = "A-5 to A-7 (Silty/Clayey Soil)"
|
| 95 |
+
else:
|
| 96 |
+
result = "A-4 (Silt)"
|
| 97 |
+
else:
|
| 98 |
+
result = "Invalid system"
|
| 99 |
+
report_summary.append(f"Soil Classification: {result}")
|
| 100 |
+
return result
|
| 101 |
+
except Exception as e:
|
| 102 |
+
return f"Error: {e}"
|
| 103 |
+
|
| 104 |
+
# ------------------------------
|
| 105 |
+
# Engineering Calculations
|
| 106 |
+
# ------------------------------
|
| 107 |
+
def convert_pressure(val, unit):
|
| 108 |
+
val = float(val)
|
| 109 |
+
if unit == "psf":
|
| 110 |
+
return val * 0.04788
|
| 111 |
+
return val
|
| 112 |
+
|
| 113 |
+
def bearing_capacity_solver(q, Nq, S, B):
|
| 114 |
+
try:
|
| 115 |
+
q_converted = convert_pressure(q, S)
|
| 116 |
+
result = q_converted * float(Nq) * float(B)
|
| 117 |
+
report_summary.append(f"Bearing Capacity: {round(result, 2)} kN/m²")
|
| 118 |
+
return f"{round(result, 2)} kN/m²"
|
| 119 |
+
except Exception as e:
|
| 120 |
+
return f"Error: {e}"
|
| 121 |
+
|
| 122 |
+
def slope_stability_solver(c, phi, gamma, height):
|
| 123 |
+
try:
|
| 124 |
+
phi = math.radians(float(phi))
|
| 125 |
+
fs = (float(c) + float(gamma) * float(height) * math.tan(phi)) / (float(gamma) * float(height))
|
| 126 |
+
report_summary.append(f"Slope Stability Factor of Safety: {round(fs, 3)}")
|
| 127 |
+
return f"{round(fs, 3)} (Factor of Safety)"
|
| 128 |
+
except Exception as e:
|
| 129 |
+
return f"Error: {e}"
|
| 130 |
+
|
| 131 |
+
def consolidation_solver(delta_sigma, mv, H):
|
| 132 |
+
try:
|
| 133 |
+
settlement = float(mv) * float(delta_sigma) * float(H)
|
| 134 |
+
report_summary.append(f"Settlement: {round(settlement, 3)} m")
|
| 135 |
+
return f"{round(settlement, 3)} m"
|
| 136 |
+
except Exception as e:
|
| 137 |
+
return f"Error: {e}"
|
| 138 |
+
|
| 139 |
+
def seepage_solver(k, i, A):
|
| 140 |
+
try:
|
| 141 |
+
q = float(k) * float(i) * float(A)
|
| 142 |
+
report_summary.append(f"Seepage Discharge: {round(q, 4)} m³/s")
|
| 143 |
+
return f"{round(q, 4)} m³/s"
|
| 144 |
+
except Exception as e:
|
| 145 |
+
return f"Error: {e}"
|
| 146 |
+
|
| 147 |
+
def compaction_solver(W, V):
|
| 148 |
+
try:
|
| 149 |
+
dry_density = float(W) / float(V)
|
| 150 |
+
report_summary.append(f"Dry Density: {round(dry_density, 2)} kN/m³")
|
| 151 |
+
return f"{round(dry_density, 2)} kN/m³"
|
| 152 |
+
except Exception as e:
|
| 153 |
+
return f"Error: {e}"
|
| 154 |
+
|
| 155 |
+
# ------------------------------
|
| 156 |
+
# PDF Report Generator
|
| 157 |
+
# ------------------------------
|
| 158 |
+
def export_full_report():
|
| 159 |
+
try:
|
| 160 |
+
file_path = "/tmp/GeoMate_Report.pdf"
|
| 161 |
+
c = canvas.Canvas(file_path, pagesize=A4)
|
| 162 |
+
width, height = A4
|
| 163 |
+
c.setFont("Helvetica", 12)
|
| 164 |
+
y = height - 50
|
| 165 |
+
for line in report_summary:
|
| 166 |
+
c.drawString(40, y, line)
|
| 167 |
+
y -= 20
|
| 168 |
+
if y < 50:
|
| 169 |
+
c.showPage()
|
| 170 |
+
c.setFont("Helvetica", 12)
|
| 171 |
+
y = height - 50
|
| 172 |
+
c.save()
|
| 173 |
+
return file_path
|
| 174 |
+
except Exception as e:
|
| 175 |
+
return f"Error: {e}"
|
| 176 |
+
|
| 177 |
+
# ------------------------------
|
| 178 |
+
# Gradio Interface
|
| 179 |
+
# ------------------------------
|
| 180 |
+
with gr.Blocks(title="GeoMate 🌍 - Soil Engineering Toolkit") as demo:
|
| 181 |
+
gr.Markdown("""
|
| 182 |
+
<div style='text-align:center; font-size:26px; font-weight:bold; color:#ff6600;'>🌍 GeoMate - Soil Engineering Toolkit</div>
|
| 183 |
+
<p style='color:#333;'>Perform all major soil-related geotechnical calculations in one place!</p>
|
| 184 |
+
""")
|
| 185 |
+
|
| 186 |
+
with gr.Tab("📷 Soil Recognizer"):
|
| 187 |
+
img_input = gr.Image(type="pil", label="Upload Soil Image")
|
| 188 |
+
img_output = gr.Textbox(label="Prediction Output")
|
| 189 |
+
img_input.change(fn=predict_soil_type, inputs=img_input, outputs=img_output)
|
| 190 |
+
|
| 191 |
+
with gr.Tab("🤖 Ask GeoMate"):
|
| 192 |
+
gr.Interface(fn=ask_soil_region,
|
| 193 |
+
inputs=gr.Textbox(placeholder="e.g., What foundation is suitable in Karachi?", lines=2),
|
| 194 |
+
outputs="text").render()
|
| 195 |
+
|
| 196 |
+
with gr.Tab("🧪 Soil Classification"):
|
| 197 |
+
system = gr.Dropdown(["USCS", "AASHTO"], label="Classification System", value="USCS")
|
| 198 |
+
ll = gr.Number(label="Liquid Limit (%)")
|
| 199 |
+
pi = gr.Number(label="Plasticity Index (%)")
|
| 200 |
+
gs = gr.Number(label="Grain Size (mm)")
|
| 201 |
+
classify_btn = gr.Button("Classify Soil")
|
| 202 |
+
classification = gr.Textbox(label="Soil Type")
|
| 203 |
+
classify_btn.click(classify_soil, [system, ll, pi, gs], classification)
|
| 204 |
+
|
| 205 |
+
with gr.Tab("🏗️ Bearing Capacity"):
|
| 206 |
+
q = gr.Number(label="Overburden Pressure")
|
| 207 |
+
q_unit = gr.Dropdown(["kN/m²", "psf", "kPa"], label="Unit", value="kN/m²")
|
| 208 |
+
nq = gr.Number(label="Nq (Bearing Capacity Factor)")
|
| 209 |
+
B = gr.Number(label="Width of Foundation (m)")
|
| 210 |
+
bc_result = gr.Textbox(label="Ultimate Bearing Capacity")
|
| 211 |
+
gr.Button("Calculate").click(bearing_capacity_solver, [q, nq, q_unit, B], bc_result)
|
| 212 |
+
|
| 213 |
+
with gr.Tab("⛰️ Slope Stability"):
|
| 214 |
+
c = gr.Number(label="Cohesion (kN/m²)")
|
| 215 |
+
phi = gr.Number(label="Friction Angle (°)")
|
| 216 |
+
gamma = gr.Number(label="Unit Weight (kN/m³)")
|
| 217 |
+
h = gr.Number(label="Height of Slope (m)")
|
| 218 |
+
fs_result = gr.Textbox(label="Factor of Safety")
|
| 219 |
+
gr.Button("Check Stability").click(slope_stability_solver, [c, phi, gamma, h], fs_result)
|
| 220 |
+
|
| 221 |
+
with gr.Tab("📉 Consolidation Settlement"):
|
| 222 |
+
ds = gr.Number(label="Change in Stress (kN/m²)")
|
| 223 |
+
mv = gr.Number(label="Volume Compressibility (m²/kN)")
|
| 224 |
+
H = gr.Number(label="Soil Layer Thickness (m)")
|
| 225 |
+
s_result = gr.Textbox(label="Settlement")
|
| 226 |
+
gr.Button("Compute Settlement").click(consolidation_solver, [ds, mv, H], s_result)
|
| 227 |
+
|
| 228 |
+
with gr.Tab("💧 Seepage"):
|
| 229 |
+
k = gr.Number(label="Permeability (m/s)")
|
| 230 |
+
i = gr.Number(label="Hydraulic Gradient")
|
| 231 |
+
A = gr.Number(label="Flow Area (m²)")
|
| 232 |
+
seep_result = gr.Textbox(label="Seepage Discharge")
|
| 233 |
+
gr.Button("Calculate Seepage").click(seepage_solver, [k, i, A], seep_result)
|
| 234 |
+
|
| 235 |
+
with gr.Tab("🔩 Compaction Test"):
|
| 236 |
+
W = gr.Number(label="Dry Weight of Soil (kN)")
|
| 237 |
+
V = gr.Number(label="Volume of Mold (m³)")
|
| 238 |
+
comp_result = gr.Textbox(label="Dry Density")
|
| 239 |
+
gr.Button("Calculate Dry Density").click(compaction_solver, [W, V], comp_result)
|
| 240 |
+
|
| 241 |
+
with gr.Tab("📄 Generate Report"):
|
| 242 |
+
pdf_output = gr.File(label="Download PDF")
|
| 243 |
+
gr.Button("Export Full Report").click(fn=export_full_report, inputs=[], outputs=pdf_output)
|
| 244 |
+
|
| 245 |
+
# Launch App
|
| 246 |
+
demo.launch()
|