george2cool36 commited on
Commit
7b2f3fb
·
verified ·
1 Parent(s): 30153cf

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +272 -0
app.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =========================
2
+ # Combined Loading Calculator — Circular (Solid/Hollow)
3
+ # Axial N, Bending (Mx, My), Torsion T → σ, τ, σ_vm, FoS
4
+ # =========================
5
+
6
+ import math
7
+ import json
8
+ import gradio as gr
9
+ import pandas as pd
10
+
11
+ # Optional tiny LLM (safe fallback to deterministic message if not available)
12
+ _USE_LLM = True
13
+ try:
14
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
15
+ MODEL_ID = "HuggingFaceTB/SmolLM2-135M-Instruct"
16
+ _tok = AutoTokenizer.from_pretrained(MODEL_ID)
17
+ _pipe = pipeline(
18
+ task="text-generation",
19
+ model=AutoModelForCausalLM.from_pretrained(MODEL_ID),
20
+ tokenizer=_tok,
21
+ )
22
+ except Exception:
23
+ _USE_LLM = False
24
+ _tok = None
25
+ _pipe = None
26
+
27
+ SCOPE_MD = r"""
28
+ ### Scope & Assumptions
29
+ - **Cross-section:** Circular shaft or beam (choose **Solid** or **Hollow**).
30
+ - **Loads:** Axial force *N* (tension +), bending moments *Mₓ* and *Mᵧ*, and torsion *T*.
31
+ - **Outputs:** Axial stress at the outer surface (from axial + bending), shear stress from torsion, **von Mises** equivalent stress, and **FoS** vs. yield strength *Sᵧ*.
32
+ - **Theory:** Linear-elastic, small deformation, pure torsion (Saint-Venant), plane sections remain plane.
33
+ *Excludes* stress concentrations, transverse shear (**V**), and buckling.
34
+ - **Units:** SI — forces in **N**, moments in **N·m**, diameters in **m**, moduli/strengths in **GPa/MPa**.
35
+ Results are shown in **MPa**.
36
+
37
+ ---
38
+
39
+ ### Valid ranges (hard checks)
40
+ - 0.01 < dₒ ≤ 2.0 m
41
+ - 0 < dᵢ < dₒ (for hollow sections)
42
+ - |N| ≤ 1×10⁶ N (± tension/compression)
43
+ - |Mₓ|, |Mᵧ|, |T| ≤ 1×10⁶ N·m
44
+ - 1 ≤ E ≤ 400 GPa
45
+ - 10 ≤ Sᵧ ≤ 3000 MPa
46
+ - 0.00001 < A ≤ 1 m²
47
+ """
48
+
49
+
50
+ def _validate(mode, d, do, di, N, Mx, My, T, Sy):
51
+ errs = []
52
+ def rng(name, val, lo, hi):
53
+ if not (lo < val <= hi):
54
+ errs.append(f"{name} must be in ({lo}, {hi}] (got {val}).")
55
+ rng("Sy [MPa]", Sy, 10, 3000)
56
+ if mode == "Solid":
57
+ rng("d [m]", d, 1e-4, 2.0)
58
+ else:
59
+ rng("Do [m]", do, 1e-4, 2.0)
60
+ rng("Di [m]", di, 0.0, do)
61
+ if di >= do:
62
+ errs.append("Hollow: require Do > Di.")
63
+ # moments/loads: allow 0 and ± large
64
+ for name, val in [("N [N]", N), ("Mx [N·m]", Mx), ("My [N·m]", My), ("T [N·m]", T)]:
65
+ if not math.isfinite(val):
66
+ errs.append(f"{name} must be finite.")
67
+ if errs:
68
+ raise ValueError("\n".join(errs))
69
+
70
+ def sect_props(mode, d, do, di):
71
+ if mode == "Solid":
72
+ A = math.pi * d**2 / 4.0
73
+ I = math.pi * d**4 / 64.0
74
+ J = math.pi * d**4 / 32.0
75
+ c = d / 2.0
76
+ outer_d = d
77
+ else:
78
+ A = math.pi * (do**2 - di**2) / 4.0
79
+ I = math.pi * (do**4 - di**4) / 64.0
80
+ J = math.pi * (do**4 - di**4) / 32.0
81
+ c = do / 2.0
82
+ outer_d = do
83
+ return A, I, J, c, outer_d
84
+
85
+ def combined_loading(mode, d, do, di, N, Mx, My, T, Sy_MPa):
86
+ _validate(mode, d, do, di, N, Mx, My, T, Sy_MPa)
87
+ A, I, J, c, outer_d = sect_props(mode, d, do, di)
88
+
89
+ # Normal stress at an outer point aligned with resultant bending
90
+ # Worst-case: take signs to maximize |sigma| → use absolute bending contributions added to axial sign
91
+ sigma_ax = N / A # Pa
92
+ sigma_bx = (Mx * c) / I if I > 0 else math.inf # Pa
93
+ sigma_by = (My * c) / I if I > 0 else math.inf # Pa
94
+
95
+ # Two extreme points (tension side / compression side). We'll report worst magnitude.
96
+ sigma_plus = sigma_ax + abs(sigma_bx) + abs(sigma_by)
97
+ sigma_minus = sigma_ax - abs(sigma_bx) - abs(sigma_by)
98
+ # Worst magnitude governs
99
+ if abs(sigma_plus) >= abs(sigma_minus):
100
+ sigma = sigma_plus
101
+ extreme_point = "+ (tension-side from bending)"
102
+ else:
103
+ sigma = sigma_minus
104
+ extreme_point = "− (compression-side from bending)"
105
+
106
+ # Shear at perimeter from torsion
107
+ tau = (T * c) / J if J > 0 else math.inf # Pa
108
+
109
+ # Von Mises
110
+ sigma_vm = (sigma**2 + 3.0 * tau**2) ** 0.5 # Pa
111
+ Sy_Pa = Sy_MPa * 1e6
112
+ fos = Sy_Pa / sigma_vm if sigma_vm > 0 else math.inf
113
+ ok = sigma_vm <= Sy_Pa
114
+
115
+ # Pretty helper
116
+ def _fmt(x, d=6):
117
+ try:
118
+ return f"{x:.{d}g}"
119
+ except Exception:
120
+ return str(x)
121
+
122
+ steps = []
123
+ steps.append("## Show the math (combined loading on circular section)")
124
+ if mode == "Solid":
125
+ steps.append(f"Mode: Solid | d = {_fmt(d)} m")
126
+ steps.append(f"A = π*d^2/4 = π*{d}^2/4 = {A:.6e} m^2")
127
+ steps.append(f"I = π*d^4/64 = π*{d}^4/64 = {I:.6e} m^4")
128
+ steps.append(f"J = π*d^4/32 = π*{d}^4/32 = {J:.6e} m^4")
129
+ steps.append(f"c = d/2 = {d}/2 = {c:.6e} m")
130
+ else:
131
+ steps.append(f"Mode: Hollow | Do = {_fmt(do)} m, Di = {_fmt(di)} m")
132
+ steps.append(f"A = π*(Do^2 - Di^2)/4 = π*({do}^2 - {di}^2)/4 = {A:.6e} m^2")
133
+ steps.append(f"I = π*(Do^4 - Di^4)/64 = π*({do}^4 - {di}^4)/64 = {I:.6e} m^4")
134
+ steps.append(f"J = π*(Do^4 - Di^4)/32 = π*({do}^4 - {di}^4)/32 = {J:.6e} m^4")
135
+ steps.append(f"c = Do/2 = {do}/2 = {c:.6e} m")
136
+
137
+ steps += [
138
+ "",
139
+ f"N = {_fmt(N)} N, Mx = {_fmt(Mx)} N·m, My = {_fmt(My)} N·m, T = {_fmt(T)} N·m, Sy = {_fmt(Sy_MPa)} MPa",
140
+ "",
141
+ "Normal stress at an outer fiber (worst-case point):",
142
+ "σ = N/A ± (Mx*c)/I ± (My*c)/I",
143
+ f"σ_ax = {N} / {A:.6e} = {sigma_ax/1e6:.6f} MPa",
144
+ f"(Mx*c)/I = ({Mx} * {c:.6e}) / ({I:.6e}) = {sigma_bx/1e6:.6f} MPa",
145
+ f"(My*c)/I = ({My} * {c:.6e}) / ({I:.6e}) = {sigma_by/1e6:.6f} MPa",
146
+ f"σ_max (reported) = {sigma/1e6:.6f} MPa at extreme point {extreme_point}",
147
+ "",
148
+ "Shear from torsion at perimeter:",
149
+ "τ = T*c/J",
150
+ f"τ = ({T} * {c:.6e}) / ({J:.6e}) = {tau/1e6:.6f} MPa",
151
+ "",
152
+ "Von Mises:",
153
+ "σ_vm = sqrt( σ^2 + 3*τ^2 )",
154
+ f"σ_vm = sqrt( ({sigma/1e6:.6f})^2 + 3*({tau/1e6:.6f})^2 ) = {sigma_vm/1e6:.6f} MPa",
155
+ f"FoS = Sy / σ_vm = {Sy_MPa} / {sigma_vm/1e6:.6f} = {fos:.3f}",
156
+ f"Verdict: {'OK (below yield)' if ok else 'NOT OK (yields by von Mises)'}"
157
+ ]
158
+ steps_md = "\n".join(steps)
159
+
160
+ results = {
161
+ "A_m2": A, "I_m4": I, "J_m4": J, "c_m": c, "outer_d_m": outer_d,
162
+ "sigma_MPa": sigma/1e6, "tau_MPa": tau/1e6,
163
+ "sigma_vm_MPa": sigma_vm/1e6, "FoS_yield": fos, "ok": bool(ok),
164
+ "extreme_point": extreme_point
165
+ }
166
+ verdict = {
167
+ "message": "OK: von Mises below yield" if ok else "NOT OK: von Mises exceeds yield",
168
+ "extreme_point": extreme_point
169
+ }
170
+
171
+ structured = {
172
+ "problem": "Combined loading on circular section (N, Mx, My, T)",
173
+ "mode": mode,
174
+ "inputs": {"N_N": N, "Mx_Nm": Mx, "My_Nm": My, "T_Nm": T, "Sy_MPa": Sy_MPa,
175
+ "d_m": d, "Do_m": do, "Di_m": di},
176
+ "section": {"A_m2": A, "I_m4": I, "J_m4": J, "c_m": c, "outer_d_m": outer_d},
177
+ "results": results,
178
+ "verdict": verdict
179
+ }
180
+ return results, verdict, steps_md, json.dumps(structured, indent=2)
181
+
182
+ def _format_chat(system_prompt: str, user_prompt: str) -> str:
183
+ if _tok is None:
184
+ return system_prompt + "\n\n" + user_prompt
185
+ msgs = [{"role":"system","content":system_prompt},{"role":"user","content":user_prompt}]
186
+ return _tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
187
+
188
+ def llm_explain(structured_message: str) -> str:
189
+ if (not _USE_LLM) or (_pipe is None) or (_tok is None):
190
+ try:
191
+ d = json.loads(structured_message)
192
+ ok = d["results"]["ok"]
193
+ vm = d["results"]["sigma_vm_MPa"]
194
+ fos = d["results"]["FoS_yield"]
195
+ return f"Quick take: von Mises = {vm:.2f} MPa (FoS={fos:.2f}) → {'OK' if ok else 'NOT OK'}."
196
+ except Exception:
197
+ return "Quick take: combined loading computed; see results."
198
+ system = "Explain to an engineering student in ONE friendly sentence; refer to the computed von Mises and FoS."
199
+ user = "Summarize whether the part yields under combined axial, bending, and torsion.\n\n" + structured_message
200
+ out = _pipe(_format_chat(system, user), max_new_tokens=80, do_sample=True, temperature=0.3, return_full_text=False)
201
+ return out[0]["generated_text"].split("\n")[0]
202
+
203
+ def run_once(mode, d, do, di, N, Mx, My, T, Sy_MPa):
204
+ try:
205
+ res, ver, steps, structured = combined_loading(
206
+ mode=mode,
207
+ d=float(d) if d is not None else 0.0,
208
+ do=float(do) if do is not None else 0.0,
209
+ di=float(di) if di is not None else 0.0,
210
+ N=float(N), Mx=float(Mx), My=float(My), T=float(T),
211
+ Sy_MPa=float(Sy_MPa)
212
+ )
213
+ df = pd.DataFrame([{
214
+ "σ (outer) [MPa]": round(res["sigma_MPa"], 3),
215
+ "τ (torsion) [MPa]": round(res["tau_MPa"], 3),
216
+ "σ_vm [MPa]": round(res["sigma_vm_MPa"], 3),
217
+ "FoS (yield)": round(res["FoS_yield"], 3),
218
+ "Extreme point": res["extreme_point"],
219
+ "Verdict": ver["message"],
220
+ }])
221
+ narrative = llm_explain(structured)
222
+ return df, narrative, steps, ""
223
+ except Exception as e:
224
+ return pd.DataFrame(), "", "", f"Input error:\n{e}"
225
+
226
+ with gr.Blocks(title="Combined Loading — Circular") as demo:
227
+ gr.Markdown("# Combined Loading Calculator — Circular (Solid/Hollow)")
228
+ gr.Markdown(SCOPE_MD)
229
+
230
+ with gr.Row():
231
+ with gr.Column():
232
+ mode = gr.Radio(["Solid", "Hollow"], value="Solid", label="Section type")
233
+ d = gr.Number(value=0.05, label="d [m] (solid diameter)")
234
+ do = gr.Number(value=0.06, label="Do [m] (outer diameter)", visible=False)
235
+ di = gr.Number(value=0.03, label="Di [m] (inner diameter)", visible=False)
236
+
237
+ def _toggle(m):
238
+ if m == "Solid":
239
+ return [gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)]
240
+ else:
241
+ return [gr.update(visible=False), gr.update(visible=True), gr.update(visible=True)]
242
+ mode.change(_toggle, inputs=[mode], outputs=[d, do, di])
243
+
244
+ with gr.Column():
245
+ gr.Markdown("### Loads & Material")
246
+ N = gr.Number(value=5e4, label="Axial N [N] (tension +)")
247
+ Mx = gr.Number(value=200.0, label="Mx [N·m]")
248
+ My = gr.Number(value=0.0, label="My [N·m]")
249
+ T = gr.Number(value=500.0, label="T [N·m]")
250
+ Sy = gr.Number(value=250.0, label="Yield strength Sy [MPa]")
251
+
252
+ run_btn = gr.Button("Compute")
253
+
254
+ gr.Markdown("### Results")
255
+ results_df = gr.Dataframe(label="Numerical results", interactive=False)
256
+
257
+ gr.Markdown("### Explain the result")
258
+ explain_md = gr.Markdown()
259
+
260
+ gr.Markdown("### Show the math")
261
+ steps_md = gr.Markdown()
262
+
263
+ err_box = gr.Textbox(label="Errors", interactive=False)
264
+
265
+ run_btn.click(
266
+ fn=run_once,
267
+ inputs=[mode, d, do, di, N, Mx, My, T, Sy],
268
+ outputs=[results_df, explain_md, steps_md, err_box]
269
+ )
270
+
271
+ if __name__ == "__main__":
272
+ demo.launch(debug=False)