File size: 1,611 Bytes
0f17a59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import gradio as gr
import pandas as pd
from datasets import load_dataset

# Load dataset from Hugging Face Hub
dataset = load_dataset("MS-God/ingredient")  # Replace with your actual dataset repo

# Convert to Pandas DataFrame
df = dataset["train"].to_pandas()

def convert_to_grams(ingredient, amount, unit):
    # Normalize ingredient names
    df["Ingredient"] = df["Ingredient"].str.strip().str.lower()
    ingredient = ingredient.strip().lower()
    
    # Find matching ingredient
    row = df[df["Ingredient"] == ingredient]
    if row.empty:
        return "Ingredient not found. Check spelling or dataset."
    
    # Get weight per unit and handle missing values
    try:
        weight_per_unit = float(row.iloc[0]["Grams"])
    except ValueError:
        return "Invalid weight data in dataset."
    
    try:
        amount = float(amount)
    except ValueError:
        return "Invalid amount input. Please enter a numeric value."
    
    # Convert units (assuming 'cup', 'tbsp', 'tsp')
    unit_conversion = {"cup": 1, "tbsp": 1/16, "tsp": 1/48}  
    unit = unit.strip().lower()
    
    if unit not in unit_conversion:
        return "Invalid unit. Please use cup, tbsp, or tsp."
    
    converted_weight = amount * unit_conversion[unit] * weight_per_unit
    return f"{converted_weight:.2f} grams"

# Create Gradio interface
demo = gr.Interface(
    fn=convert_to_grams,
    inputs=["text", "text", "text"],
    outputs="text",
    title="Ingredient to Grams Converter",
    description="Enter an ingredient, amount, and unit (e.g., '1 cup'), and get the weight in grams."
)

demo.launch()