SabaAnver commited on
Commit
4168d77
·
verified ·
1 Parent(s): 05a1a4d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +140 -0
app.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ # Simple Unit Converter for Hugging Face Spaces (Gradio)
3
+ # No models or APIs required — pure Python
4
+
5
+ import gradio as gr
6
+
7
+ # Base units: Length -> meter, Mass -> kilogram, Volume -> liter
8
+ UNITS = {
9
+ "Length": {
10
+ "m": 1.0,
11
+ "cm": 0.01,
12
+ "km": 1000.0,
13
+ "in": 0.0254,
14
+ "ft": 0.3048,
15
+ "yd": 0.9144,
16
+ "mi": 1609.344,
17
+ },
18
+ "Mass": {
19
+ "kg": 1.0,
20
+ "g": 0.001,
21
+ "lb": 0.45359237,
22
+ "oz": 0.028349523125,
23
+ },
24
+ "Volume": {
25
+ "L": 1.0,
26
+ "mL": 0.001,
27
+ "gal": 3.785411784, # US liquid gallon
28
+ "qt": 0.946352946, # US liquid quart
29
+ "cup": 0.2365882365, # US cup
30
+ }
31
+ }
32
+
33
+ TEMP_UNITS = ["C", "F", "K"]
34
+ CATEGORIES = ["Length", "Mass", "Temperature", "Volume"]
35
+
36
+
37
+ def convert_temperature(value: float, from_u: str, to_u: str) -> float:
38
+ if from_u == "K" and value < 0:
39
+ raise ValueError("Kelvin cannot be negative.")
40
+ # to Celsius
41
+ if from_u == "C":
42
+ c = value
43
+ elif from_u == "F":
44
+ c = (value - 32.0) * 5.0 / 9.0
45
+ elif from_u == "K":
46
+ c = value - 273.15
47
+ else:
48
+ raise ValueError("Unknown temperature unit.")
49
+ # from Celsius to target
50
+ if to_u == "C":
51
+ return c
52
+ elif to_u == "F":
53
+ return c * 9.0 / 5.0 + 32.0
54
+ elif to_u == "K":
55
+ return c + 273.15
56
+ else:
57
+ raise ValueError("Unknown temperature unit.")
58
+
59
+
60
+ def convert_via_base(value: float, category: str, from_u: str, to_u: str) -> float:
61
+ factors = UNITS[category]
62
+ if from_u not in factors or to_u not in factors:
63
+ raise ValueError("Unsupported unit for this category.")
64
+ base_val = value * factors[from_u] # to base (meter/kg/liter)
65
+ return base_val / factors[to_u]
66
+
67
+
68
+ def convert(category: str, value, from_unit: str, to_unit: str, decimals: int):
69
+ if value is None or str(value).strip() == "":
70
+ return "Please enter a number."
71
+ try:
72
+ value = float(value)
73
+ except:
74
+ return "Please enter a valid number (e.g., 12.5)."
75
+ try:
76
+ if category == "Temperature":
77
+ result = convert_temperature(value, from_unit, to_unit)
78
+ else:
79
+ result = convert_via_base(value, category, from_unit, to_unit)
80
+ fmt = f"{{:.{int(decimals)}f}}"
81
+ return f"{value} {from_unit} = {fmt.format(result)} {to_unit}"
82
+ except Exception as e:
83
+ return f"Error: {e}"
84
+
85
+
86
+ def units_for_category(category: str):
87
+ if category == "Temperature":
88
+ choices = TEMP_UNITS
89
+ else:
90
+ choices = list(UNITS[category].keys())
91
+ default_from = choices[0]
92
+ default_to = choices[1] if len(choices) > 1 else choices[0]
93
+ return (
94
+ gr.update(choices=choices, value=default_from),
95
+ gr.update(choices=choices, value=default_to),
96
+ )
97
+
98
+
99
+ with gr.Blocks(title="Simple Unit Converter") as demo:
100
+ gr.Markdown(
101
+ """
102
+ # Simple Unit Converter
103
+ A tiny web app to convert units (Length, Mass, Volume, Temperature).
104
+ No models or APIs — pure Python.
105
+ """
106
+ )
107
+
108
+ with gr.Row():
109
+ category = gr.Dropdown(CATEGORIES, value="Length", label="Category")
110
+ decimals = gr.Slider(minimum=0, maximum=10, step=1, value=3, label="Decimal places")
111
+
112
+ value_in = gr.Number(label="Input value", value=1.0)
113
+
114
+ with gr.Row():
115
+ from_unit = gr.Dropdown(list(UNITS["Length"].keys()), value="m", label="From unit")
116
+ to_unit = gr.Dropdown(list(UNITS["Length"].keys()), value="ft", label="To unit")
117
+
118
+ convert_btn = gr.Button("Convert")
119
+ output = gr.Textbox(label="Result", lines=1)
120
+
121
+ category.change(fn=units_for_category, inputs=category, outputs=[from_unit, to_unit])
122
+
123
+ convert_btn.click(fn=convert, inputs=[category, value_in, from_unit, to_unit, decimals], outputs=output)
124
+
125
+ gr.Examples(
126
+ examples=[
127
+ ["Length", 1, "m", "ft", 3],
128
+ ["Length", 12, "in", "cm", 2],
129
+ ["Mass", 2.5, "kg", "lb", 3],
130
+ ["Volume", 3, "L", "gal", 4],
131
+ ["Temperature", 100, "C", "F", 1],
132
+ ["Temperature", 300, "K", "C", 2],
133
+ ],
134
+ inputs=[category, value_in, from_unit, to_unit, decimals],
135
+ label="Examples (click to fill the form)"
136
+ )
137
+
138
+ if __name__ == "__main__":
139
+ # Spaces runs your script and will serve the Gradio app automatically.
140
+ demo.launch()