Umar4321 commited on
Commit
a0f06fd
·
verified ·
1 Parent(s): 01e9669

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -0
app.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ """Simple Unit Converter (Gradio) for Hugging Face Spaces.
3
+ - Put this file at the repo root as `app.py` (Spaces uses this as the entry point).
4
+ - Minimal dependencies: gradio only.
5
+ """
6
+
7
+ import gradio as gr
8
+
9
+ # --- Unit factors to a base unit ---
10
+ UNITS = {
11
+ "Mass": {
12
+ "kg": 1.0,
13
+ "g": 0.001,
14
+ "lb (pound)": 0.45359237,
15
+ "oz (ounce)": 0.028349523125
16
+ },
17
+ "Length": {
18
+ "m": 1.0,
19
+ "cm": 0.01,
20
+ "mm": 0.001,
21
+ "ft (foot)": 0.3048,
22
+ "in (inch)": 0.0254
23
+ },
24
+ "Volume": {
25
+ "L (liter)": 1.0,
26
+ "mL (milliliter)": 0.001,
27
+ "US gallon": 3.785411784,
28
+ "US quart": 0.946352946
29
+ },
30
+ # Temperature handled with formulas instead of factors
31
+ "Temperature": ["C", "F", "K"]
32
+ }
33
+
34
+ def update_units(category):
35
+ """Update From/To dropdowns when Category changes."""
36
+ if category == "Temperature":
37
+ choices = UNITS["Temperature"]
38
+ else:
39
+ choices = list(UNITS[category].keys())
40
+ from_default = choices[0]
41
+ to_default = choices[1] if len(choices) > 1 else choices[0]
42
+ return gr.update(choices=choices, value=from_default), gr.update(choices=choices, value=to_default)
43
+
44
+ def convert(value, category, from_unit, to_unit, precision):
45
+ """Convert `value` from `from_unit` to `to_unit` inside `category`."""
46
+ # Input validation
47
+ try:
48
+ val = float(value)
49
+ except Exception:
50
+ return "❗ Enter a valid number."
51
+
52
+ # quick return if same unit
53
+ if from_unit == to_unit:
54
+ fmt = f"{{:.{precision}f}}"
55
+ return f"{fmt.format(val)} {from_unit} = {fmt.format(val)} {to_unit}"
56
+
57
+ # Temperature conversions (Celsius as intermediate)
58
+ if category == "Temperature":
59
+ # to Celsius
60
+ if from_unit == "C":
61
+ c = val
62
+ elif from_unit == "F":
63
+ c = (val - 32) * 5.0 / 9.0
64
+ elif from_unit == "K":
65
+ c = val - 273.15
66
+ else:
67
+ return "❗ Unknown temperature unit."
68
+
69
+ # from Celsius to target
70
+ if to_unit == "C":
71
+ res = c
72
+ elif to_unit == "F":
73
+ res = c * 9.0 / 5.0 + 32
74
+ elif to_unit == "K":
75
+ res = c + 273.15
76
+ else:
77
+ return "❗ Unknown temperature unit."
78
+ else:
79
+ # factor-based conversion: value -> base -> target
80
+ factors = UNITS[category]
81
+ try:
82
+ f_from = factors[from_unit]
83
+ f_to = factors[to_unit]
84
+ except KeyError:
85
+ return "❗ Unknown unit for selected category."
86
+ value_in_base = val * f_from
87
+ res = value_in_base / f_to
88
+
89
+ fmt = f"{{:.{precision}f}}"
90
+ return f"{fmt.format(val)} {from_unit} = {fmt.format(res)} {to_unit}"
91
+
92
+ # --- Build Gradio UI ---
93
+ with gr.Blocks() as demo:
94
+ gr.Markdown("## 🔁 Simple Unit Converter\nChoose category, units, value, then press Convert.")
95
+ with gr.Row():
96
+ category_dd = gr.Dropdown(choices=list(UNITS.keys()), value="Mass", label="Category")
97
+ precision = gr.Slider(minimum=0, maximum=6, step=1, value=4, label="Decimals")
98
+ with gr.Row():
99
+ from_dd = gr.Dropdown(choices=list(UNITS["Mass"].keys()), value="kg", label="From unit")
100
+ to_dd = gr.Dropdown(choices=list(UNITS["Mass"].keys()), value="g", label="To unit")
101
+ value_in = gr.Number(value=1.0, label="Value to convert")
102
+ convert_btn = gr.Button("Convert")
103
+ output_txt = gr.Textbox(label="Result", interactive=False)
104
+
105
+ # callbacks
106
+ category_dd.change(fn=update_units, inputs=category_dd, outputs=[from_dd, to_dd])
107
+ convert_btn.click(fn=convert, inputs=[value_in, category_dd, from_dd, to_dd, precision], outputs=output_txt)
108
+
109
+ # Entry point for Spaces
110
+ if __name__ == "__main__":
111
+ demo.launch()