Basitali0311/Unit_Conversion_App
0
1import streamlit as st2from pint import UnitRegistry3import base644 5# Initialize UnitRegistry6ureg = UnitRegistry()7Q_ = ureg.Quantity8 9# --- Function to set background ---10def set_bg_image(image_file):11 with open(image_file, "rb") as f:12 encoded_string = base64.b64encode(f.read()).decode()13 st.markdown(14 f"""15 <style>16 .stApp {{17 background-image: url(data:image/{"png"};base64,{encoded_string});18 background-size: cover;19 }}20 </style>21 """,22 unsafe_allow_html=True23 )24 25# Set a chemical engineering themed background image26# You'll need to save an image named 'chemical_engineering_background.png' in the same directory27set_bg_image("chemical_engineering_background.png")28 29# --- App setup ---30st.set_page_config(page_title="⚛️ ChemEng Unit Converter 🧪", layout="wide")31 32# Custom CSS for a more attractive interface33st.markdown(34 """35 <style>36 .title {37 color: #007bff; /* A nice blue */38 font-size: 2.5em;39 text-align: center;40 margin-bottom: 1em;41 }42 .subheader {43 color: #6c757d; /* A greyish tone */44 font-size: 1.2em;45 text-align: center;46 margin-bottom: 1.5em;47 }48 .st-selectbox label, .st-number-input label {49 color: #343a40; /* Dark grey for labels */50 }51 .st-form {52 background-color: rgba(255, 255, 255, 0.8); /* Semi-transparent white background for the form */53 padding: 20px;54 border-radius: 10px;55 box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);56 margin-bottom: 2em;57 }58 .st-form-submit-button {59 background-color: #28a745; /* A vibrant green for the submit button */60 color: white;61 }62 .st-success {63 color: #198754; /* Success message color */64 background-color: #d4edda;65 border: 1px solid #c3e6cb;66 padding: 10px;67 border-radius: 5px;68 margin-top: 1em;69 }70 .st-error {71 color: #dc3545; /* Error message color */72 background-color: #f8d7da;73 border: 1px solid #f5c2c7;74 padding: 10px;75 border-radius: 5px;76 margin-top: 1em;77 }78 .st-expander {79 background-color: rgba(255, 255, 255, 0.7);80 border-radius: 5px;81 margin-top: 1em;82 }83 .st-caption {84 color: #868e96; /* Light grey for caption */85 text-align: center;86 margin-top: 1em;87 }88 </style>89 """,90 unsafe_allow_html=True91)92 93st.markdown("<h1 class='title'>⚛️ Chemical Engineering Unit Converter 🧪</h1>", unsafe_allow_html=True)94st.markdown("<p class='subheader'>Convert units commonly used in chemical engineering with ease!</p>", unsafe_allow_html=True)95 96# --- Updated Unit Options Dictionary with more Chemical Engineering Conversions ---97unit_options = {98 "Pressure": ["pascal", "kilopascal", "megapascal", "atmosphere", "bar", "psi", "torr", "mmHg", "inHg", "mbar"],99 "Temperature": ["degC", "degF", "kelvin", "degR"],100 "Flow Rate (Volume)": ["meter**3/second", "liter/minute", "cubic_foot/minute", "gallon/minute", "barrel/day", "MLD (million liters per day)"],101 "Flow Rate (Mass)": ["kilogram/second", "pound/hour"],102 "Concentration (Molar)": ["mole/liter", "kmol/m**3"],103 "Concentration (Mass)": ["gram/liter", "milligram/milliliter", "ppm", "ppb", "weight percent"],104 "Energy": ["joule", "kilojoule", "megajoule", "calorie", "kilocalorie", "btu", "kWh"],105 "Length": ["meter", "centimeter", "millimeter", "inch", "foot", "kilometer", "mile"],106 "Mass": ["gram", "kilogram", "milligram", "pound", "ton (metric)", "ton (US)"],107 "Viscosity (Dynamic)": ["pascal*second", "poise", "centipoise", "lbf*s/ft**2"],108 "Viscosity (Kinematic)": ["meter**2/second", "stokes", "centistokes"],109 "Density": ["kilogram/meter**3", "gram/centimeter**3", "pound/foot**3", "gram/liter", "SG (Specific Gravity)"],110 "Heat Transfer Coefficient": ["W/(m**2*K)", "BTU/(hr*ft**2*degF)"],111 "Thermal Conductivity": ["W/(m*K)", "BTU/(hr*ft*degF)"],112 "Power": ["watt", "kilowatt", "horsepower"],113 "Force": ["newton", "dyne", "lbf"],114 "Area": ["meter**2", "centimeter**2", "foot**2", "inch**2"]115}116 117# --- Conversion Logic ---118def convert_units(value, from_unit_str, to_unit_str):119 try:120 if from_unit_str == "SG (Specific Gravity)" and to_unit_str.startswith("kilogram/meter**3"):121 return f"{float(value) * 1000:.6g} kilogram/meter**3"122 elif from_unit_str.startswith("kilogram/meter**3") and to_unit_str == "SG (Specific Gravity)":123 return f"{float(value) / 1000:.6g}"124 elif from_unit_str == "SG (Specific Gravity)" and to_unit_str.startswith("gram/centimeter**3"):125 return f"{float(value):.6g} gram/centimeter**3"126 elif from_unit_str.startswith("gram/centimeter**3") and to_unit_str == "SG (Specific Gravity)":127 return f"{float(value):.6g}"128 elif from_unit_str == "weight percent" and to_unit_str in ["ppm", "ppb"]:129 if to_unit_str == "ppm":130 return f"{float(value) * 10000:.6g} ppm"131 elif to_unit_str == "ppb":132 return f"{float(value) * 10000000:.6g} ppb"133 elif from_unit_str in ["ppm", "ppb"] and to_unit_str == "weight percent":134 if from_unit_str == "ppm":135 return f"{float(value) / 10000:.6g} weight percent"136 elif from_unit_str == "ppb":137 return f"{float(value) / 10000000:.6g} weight percent"138 elif from_unit_str == "MLD (million liters per day)" and to_unit_str == "meter**3/second":139 return f"{float(value) * 1000000 / (24 * 3600):.6g} meter**3/second"140 elif from_unit_str == "meter**3/second" and to_unit_str == "MLD (million liters per day)":141 return f"{float(value) * (24 * 3600) / 1000000:.6g} MLD"142 else:143 quantity = Q_(value, from_unit_str.replace(" ", "_").replace("**", "^"))144 converted = quantity.to(to_unit_str.replace(" ", "_").replace("**", "^"))145 return f"{converted.magnitude:.6g} {converted.units}"146 except Exception as e:147 return f"Error: {str(e)}"148 149# --- Input Form ---150with st.form("converter_form"):151 category = st.selectbox("Choose a category", list(unit_options.keys()))152 value = st.number_input("Enter the value to convert:", value=1.0)153 from_unit = st.selectbox("From unit", unit_options[category])154 to_unit = st.selectbox("To unit", unit_options[category])155 submitted = st.form_submit_button("Convert")156 157if submitted:158 result = convert_units(value, from_unit, to_unit)159 if "Error" not in result:160 st.success(f"Converted value: {result}")161 else:162 st.error(result)163 164# --- Notes and Unit Help ---165with st.expander("ℹ️ Conversion Notes & Unit Help"):166 st.markdown("""167 This unit converter supports a wide range of chemical engineering units using the powerful `pint` library.168 169 **Common Categories:**170 - **Pressure**: bar, atm, psi, Pa, mmHg, inHg, mbar.171 - **Temperature**: °C, °F, K, °R.172 - **Flow Rate (Volume)**: m³/s, L/min, ft³/min, gal/min, barrel/day, MLD.173 - **Flow Rate (Mass)**: kg/s, lb/hr.174 - **Concentration (Molar)**: mol/L, kmol/m³.175 - **Concentration (Mass)**: g/L, mg/mL, ppm, ppb, weight percent.176 - **Energy**: J, kJ, MJ, cal, kcal, BTU, kWh.177 - **Length**: m, cm, mm, in, ft, km, mile.178 - **Mass**: g, kg, mg, lb, ton (metric), ton (US).179 - **Viscosity (Dynamic)**: Pa·s, P (poise), cP (centipoise), lbf·s/ft².180 - **Viscosity (Kinematic)**: m²/s, St (stokes), cSt (centistokes).181 - **Density**: kg/m³, g/cm³, lb/ft³, g/L, SG (Specific Gravity).182 - **Heat Transfer Coefficient**: W/(m²·K), BTU/(hr·ft²·°F).183 - **Thermal Conductivity**: W/(m·K), BTU/(hr·ft·°F).184 - **Power**: W, kW, horsepower.185 - **Force**: N, dyne, lbf.186 - **Area**: m², cm², ft², in².187 188 **Important Notes:**189 - **Specific Gravity (SG)** is dimensionless. When converting to density units, it's assumed to be relative to water (approximately 1000 kg/m³ or 1 g/cm³).190 - **ppm** (parts per million) and **ppb** (parts per billion) are mass-based unless otherwise specified in a specific context. This converter assumes mass basis for conversion with weight percent.191 - **MLD** stands for Million Liters per Day, a common unit for large-scale water flow rates.192 - Ensure you select the correct sub-category for flow rate (Volume or Mass) for accurate conversions.193 194 ✨ Powered by the amazing [pint](https://pint.readthedocs.io/) library.195 """)196 197st.markdown("---")198st.caption("Developed with passion by a Chemical Engineer for the ChemEng Community.")