Spaces:
Sleeping
Sleeping
Upload app.py with huggingface_hub
Browse files
app.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from transformers import pipeline, set_seed
|
| 5 |
+
|
| 6 |
+
SCOPE = """
|
| 7 |
+
**Scope:** DC, steady-state Ohm's Law.
|
| 8 |
+
**Assumptions:** Ideal components; temperature effects ignored.
|
| 9 |
+
**Units:** V (volts), I (amps), R (ohms).
|
| 10 |
+
**Valid ranges:** 0 ≤ V ≤ 1000, 0 ≤ I ≤ 100, 0.1 ≤ R ≤ 1e6.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
set_seed(42)
|
| 14 |
+
try:
|
| 15 |
+
explain_llm = pipeline("text2text-generation", model="google/flan-t5-small")
|
| 16 |
+
except Exception as e:
|
| 17 |
+
print("LLM pipeline init failed; using fallback text only.", e)
|
| 18 |
+
explain_llm = None
|
| 19 |
+
|
| 20 |
+
def validate(target, V, I, R):
|
| 21 |
+
errs = []
|
| 22 |
+
if target != "Voltage (V)" and not (0 <= V <= 1000): errs.append("V must be 0–1000 V.")
|
| 23 |
+
if target != "Current (I)" and not (0 <= I <= 100): errs.append("I must be 0–100 A.")
|
| 24 |
+
if target != "Resistance (R)"and not (0.1 <= R <= 1e6):errs.append("R must be 0.1–1e6 Ω.")
|
| 25 |
+
if target == "Current (I)" and R == 0: errs.append("R cannot be 0 for I = V/R.")
|
| 26 |
+
if target == "Resistance (R)"and I == 0: errs.append("I cannot be 0 for R = V/I.")
|
| 27 |
+
return errs
|
| 28 |
+
|
| 29 |
+
def compute_structured(target, V, I, R):
|
| 30 |
+
if target == "Voltage (V)":
|
| 31 |
+
value = I * R
|
| 32 |
+
steps = [f"Use V = I·R", f"V = {I} A × {R} Ω = {value} V"]
|
| 33 |
+
out = {"quantity":"V","value":value,"units":"V"}
|
| 34 |
+
elif target == "Current (I)":
|
| 35 |
+
value = V / R
|
| 36 |
+
steps = [f"Use I = V/R", f"I = {V} V ÷ {R} Ω = {value} A"]
|
| 37 |
+
out = {"quantity":"I","value":value,"units":"A"}
|
| 38 |
+
else:
|
| 39 |
+
value = V / I
|
| 40 |
+
steps = [f"Use R = V/I", f"R = {V} V ÷ {I} A = {value} Ω"]
|
| 41 |
+
out = {"quantity":"R","value":value,"units":"Ω"}
|
| 42 |
+
|
| 43 |
+
return {
|
| 44 |
+
"calculation":"Ohm's Law",
|
| 45 |
+
"equations":{"V":"V=I·R","I":"I=V/R","R":"R=V/I"},
|
| 46 |
+
"target":target,
|
| 47 |
+
"inputs":{"V":V,"I":I,"R":R,"units":{"V":"V","I":"A","R":"Ω"}},
|
| 48 |
+
"steps":steps,
|
| 49 |
+
"output":out
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
def explain(_data: dict) -> str:
|
| 53 |
+
"""
|
| 54 |
+
Always ask the LLM to explain what Ohm's Law is; fallback if unavailable.
|
| 55 |
+
"""
|
| 56 |
+
prompt = (
|
| 57 |
+
"Explain Ohm’s Law for a non-expert in <=80 words. "
|
| 58 |
+
"Use symbols ×, ·, and Ω (no Unicode escapes). "
|
| 59 |
+
"Include the three forms (V = I·R, I = V/R, R = V/I) and list the units."
|
| 60 |
+
)
|
| 61 |
+
if explain_llm is not None:
|
| 62 |
+
try:
|
| 63 |
+
txt = explain_llm(prompt, do_sample=False, num_beams=1, max_new_tokens=120)[0]["generated_text"].strip()
|
| 64 |
+
if txt:
|
| 65 |
+
return (txt.replace("\u00b7","·")
|
| 66 |
+
.replace("\u00D7","×").replace("\u00d7","×")
|
| 67 |
+
.replace("\u03a9","Ω").replace("\u03A9","Ω"))
|
| 68 |
+
except Exception as e:
|
| 69 |
+
print("LLM explanation failed:", e)
|
| 70 |
+
return ("Ohm’s Law relates voltage (V), current (I), and resistance (R): "
|
| 71 |
+
"V = I·R, I = V/R, R = V/I. Units: V (volts), A (amps), Ω (ohms).")
|
| 72 |
+
|
| 73 |
+
def run(target, V, I, R):
|
| 74 |
+
errs = validate(target, V, I, R)
|
| 75 |
+
if errs: raise gr.Error("\n".join(errs))
|
| 76 |
+
data = compute_structured(target, V, I, R)
|
| 77 |
+
df = pd.DataFrame([{
|
| 78 |
+
"Target": data["target"],
|
| 79 |
+
"V (V)": data["inputs"]["V"],
|
| 80 |
+
"I (A)": data["inputs"]["I"],
|
| 81 |
+
"R (Ω)": data["inputs"]["R"],
|
| 82 |
+
"Result": f'{data["output"]["quantity"]} = {data["output"]["value"]} {data["output"]["units"]}'
|
| 83 |
+
}])
|
| 84 |
+
return df, json.dumps(data, indent=2), explain(data)
|
| 85 |
+
|
| 86 |
+
with gr.Blocks(title="Ohm's Law — see the math") as demo:
|
| 87 |
+
gr.Markdown("# 🔌 Ohm's Law — Deterministic Calculator")
|
| 88 |
+
gr.Markdown(SCOPE)
|
| 89 |
+
with gr.Row():
|
| 90 |
+
with gr.Column():
|
| 91 |
+
target = gr.Radio(["Voltage (V)","Current (I)","Resistance (R)"], value="Voltage (V)", label="Compute")
|
| 92 |
+
V = gr.Number(value=12.0, label="Voltage V (V) [ignored if computing V]")
|
| 93 |
+
I = gr.Number(value=2.0, label="Current I (A) [ignored if computing I]")
|
| 94 |
+
R = gr.Number(value=6.0, label="Resistance R (Ω) [ignored if computing R]")
|
| 95 |
+
btn = gr.Button("Compute", variant="primary")
|
| 96 |
+
with gr.Column():
|
| 97 |
+
with gr.Tabs():
|
| 98 |
+
with gr.Tab("Results"):
|
| 99 |
+
out_table = gr.Dataframe(label="Results", interactive=False)
|
| 100 |
+
with gr.Tab("Explanation"):
|
| 101 |
+
out_expl = gr.Markdown(value="_Explanation will appear here after you click **Compute**._")
|
| 102 |
+
with gr.Tab("Structured JSON"):
|
| 103 |
+
out_json = gr.Code(label="Structured output (JSON)", language="json")
|
| 104 |
+
inputs = [target, V, I, R]
|
| 105 |
+
btn.click(run, inputs=inputs, outputs=[out_table, out_json, out_expl])
|
| 106 |
+
gr.Examples(
|
| 107 |
+
inputs=inputs,
|
| 108 |
+
examples=[
|
| 109 |
+
["Voltage (V)", 0.0, 2.0, 50.0],
|
| 110 |
+
["Current (I)", 12.0, 0.0, 6.0],
|
| 111 |
+
["Resistance (R)", 5.0, 0.01, 0.0]
|
| 112 |
+
],
|
| 113 |
+
label="Examples"
|
| 114 |
+
)
|
| 115 |
+
if __name__ == "__main__":
|
| 116 |
+
demo.launch()
|