import torch import torch.nn as nn import torch.nn.functional as F import gradio as gr # --- Define Model --- class FruitYieldModel(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(3, 2) def forward(self, x): return self.linear(x) # --- Load & Train Data --- inputs = torch.tensor([ [73, 67, 43], [91, 88, 64], [87, 134, 58], [102, 43, 37], [69, 96, 70], [76, 112, 54], [84, 70, 45], [95, 122, 66], [79, 89, 49], [88, 111, 52], [85, 95, 61], [90, 84, 57], [93, 128, 60], [97, 77, 41], [81, 102, 63] ], dtype=torch.float32) targets = torch.tensor([ [56, 70], [81, 101], [119, 133], [22, 37], [103, 119], [68, 89], [73, 84], [110, 125], [69, 91], [95, 108], [88, 99], [86, 105], [120, 130], [39, 61], [97, 112] ], dtype=torch.float32) # --- Model Training --- model = FruitYieldModel() model.load_state_dict(torch.load("fruit_model.pth", map_location=torch.device("cpu"))) model.eval() # --- Prediction Function --- def predict(temp, rain, humidity): with torch.no_grad(): inp = torch.tensor([[temp, rain, humidity]], dtype=torch.float32) output = model(inp).numpy().flatten() return { "Apple Yield": round(output[0], 2), "Orange Yield": round(output[1], 2) } # --- Gradio Interface --- interface = gr.Interface( fn=predict, inputs=[ gr.Number(label="Temperature (°F)"), gr.Number(label="Rainfall (mm)"), gr.Number(label="Humidity (%)") ], outputs=gr.Label(num_top_classes=2), title="Fruit Yield Predictor", description="Enter environmental data to predict apple and orange yields." ) if __name__ == "__main__": interface.launch()