GodfreyOwino commited on
Commit
f75d6da
·
verified ·
1 Parent(s): 7abb756

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -0
app.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from fastapi import FastAPI
3
+ from pydantic import BaseModel
4
+ from huggingface_hub import hf_hub_download, HfApi
5
+ import joblib
6
+ import os
7
+ from datetime import datetime, timedelta
8
+ import pandas as pd
9
+
10
+ REPO_ID = "GodfreyOwino/NPK_needs_mode2"
11
+ FILENAME = "npk_needs_model.joblib"
12
+ UPDATE_FREQUENCY = timedelta(days=1)
13
+
14
+ class InputData(BaseModel):
15
+ crop_name: str
16
+ target_yield: float
17
+ field_size: float
18
+ ph: float
19
+ organic_carbon: float
20
+ nitrogen: float
21
+ phosphorus: float
22
+ potassium: float
23
+ soil_moisture: float
24
+
25
+ def get_latest_model():
26
+ try:
27
+ api = HfApi()
28
+ remote_info = api.model_info(repo_id=REPO_ID)
29
+ remote_mtime = remote_info.lastModified
30
+
31
+ cached_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME)
32
+
33
+ if os.path.exists(cached_path):
34
+ local_mtime = datetime.fromtimestamp(os.path.getmtime(cached_path))
35
+
36
+ if datetime.now() - local_mtime < UPDATE_FREQUENCY:
37
+ print("Using cached model (checked recently)")
38
+ return joblib.load(cached_path)
39
+
40
+ if remote_mtime > local_mtime:
41
+ print("Downloading updated model")
42
+ cached_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME, force_download=True)
43
+ else:
44
+ print("Cached model is up-to-date")
45
+ else:
46
+ print("Downloading model for the first time")
47
+ cached_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME)
48
+
49
+ except Exception as e:
50
+ print(f"Error checking/downloading model: {e}")
51
+ print(f"Error type: {type(e)}")
52
+ print(f"Error details: {str(e)}")
53
+ raise Exception("Unable to download or find the model.")
54
+
55
+ return joblib.load(cached_path)
56
+
57
+ def predict(crop_name, target_yield, field_size, ph, organic_carbon, nitrogen, phosphorus, potassium, soil_moisture):
58
+ try:
59
+ model = get_latest_model()
60
+
61
+ input_data = {
62
+ 'crop_name': [crop_name],
63
+ 'target_yield': [target_yield],
64
+ 'field_size': [field_size],
65
+ 'ph': [ph],
66
+ 'organic_carbon': [organic_carbon],
67
+ 'nitrogen': [nitrogen],
68
+ 'phosphorus': [phosphorus],
69
+ 'potassium': [potassium],
70
+ 'soil_moisture': [soil_moisture]
71
+ }
72
+
73
+ input_df = pd.DataFrame(input_data)
74
+
75
+ prediction = model.predict(input_df)
76
+
77
+ results = {
78
+ 'nitrogen_need': float(prediction[0][0]),
79
+ 'phosphorus_need': float(prediction[0][1]),
80
+ 'potassium_need': float(prediction[0][2]),
81
+ 'organic_matter_need': float(prediction[0][3]),
82
+ 'lime_need': float(prediction[0][4])
83
+ }
84
+
85
+ return results
86
+ except Exception as e:
87
+ return {"error": str(e)}
88
+
89
+ iface = gr.Interface(
90
+ fn=predict,
91
+ inputs=[
92
+ gr.Textbox(label="Crop Name"),
93
+ gr.Number(label="Target Yield"),
94
+ gr.Number(label="Field Size"),
95
+ gr.Number(label="pH"),
96
+ gr.Number(label="Organic Carbon"),
97
+ gr.Number(label="Nitrogen"),
98
+ gr.Number(label="Phosphorus"),
99
+ gr.Number(label="Potassium"),
100
+ gr.Number(label="Soil Moisture")
101
+ ],
102
+ outputs=gr.JSON(label="Prediction Results"),
103
+ title="NPK Needs Prediction",
104
+ description="Enter soil and crop details to predict NPK needs."
105
+ )
106
+
107
+ iface.launch()