RUVNE commited on
Commit
dda7755
·
1 Parent(s): f8340db

feat: redis buat sendiri

Browse files
Files changed (1) hide show
  1. app.py +40 -17
app.py CHANGED
@@ -1,18 +1,19 @@
1
  from fastapi import FastAPI, UploadFile, File
2
  from fastapi.middleware.cors import CORSMiddleware
3
- from transformers import pipeline
4
- from PIL import Image
5
  from PIL import Image
6
  import numpy as np
7
  import uvicorn
8
  from tensorflow.keras.models import load_model
9
- from transformers import (AutoTokenizer)
10
  import os
 
 
 
11
 
12
  # === Inisialisasi FastAPI ===
13
  app = FastAPI()
14
 
15
- # === CORS (opsional) ===
16
  app.add_middleware(
17
  CORSMiddleware,
18
  allow_origins=["*"],
@@ -21,14 +22,17 @@ app.add_middleware(
21
  allow_headers=["*"],
22
  )
23
 
24
- # === Load Model Klasifikasi Gambar ===
25
- model_path = os.path.join(os.path.dirname(__file__), "saved_model", "multidisease_model.h5")
 
 
 
 
 
26
  if not os.path.exists(model_path):
27
  raise FileNotFoundError(f"Model tidak ditemukan di path: {model_path}")
28
  image_model = load_model(model_path)
29
 
30
-
31
- # Label (ubah sesuai model Anda)
32
  label_map = {
33
  0: "BacterialBlight",
34
  1: "Blast",
@@ -46,7 +50,7 @@ label_descriptions = {
46
  "Tungro": "Penyakit virus yang membuat daun menguning dan pertumbuhan terhambat.",
47
  }
48
 
49
- # === Load Chatbot Pipeline ===
50
  chatbot = pipeline(
51
  "text-generation",
52
  model="ARusDian/AgroLens-Chatbot",
@@ -55,29 +59,46 @@ chatbot = pipeline(
55
 
56
 
57
  def preprocess_image(image: Image.Image):
58
- image = image.resize((224, 224)) # sesuaikan ukuran input model
59
- img_array = np.array(image) / 255.0 # normalisasi
60
- img_array = np.expand_dims(img_array, axis=0) # tambahkan batch dimensi
61
  return img_array
62
 
63
 
64
- # === Endpoint: Klasifikasi Gambar ===
 
 
 
 
 
 
65
  @app.post("/predict-image")
66
  async def predict_image(file: UploadFile = File(...)):
67
  image = Image.open(file.file).convert("RGB")
68
- input_tensor = preprocess_image(image)
 
 
 
69
 
 
70
  pred = np.argmax(image_model.predict(input_tensor), axis=1)[0]
71
  label = label_map.get(pred, "Tidak dikenal")
72
  description = label_descriptions.get(label, "-")
73
 
74
- return {"prediction": label, "description": description}
 
 
75
 
76
 
77
- # === Endpoint: Chatbot Deskripsi Penyakit ===
78
  @app.post("/chatbot")
79
  async def describe(prompt: dict):
80
  text = prompt["prompt"]
 
 
 
 
 
81
  tokenizer = AutoTokenizer.from_pretrained("ARusDian/AgroLens-Chatbot")
82
  result = chatbot(
83
  text,
@@ -89,9 +110,11 @@ async def describe(prompt: dict):
89
  do_sample=True,
90
  eos_token_id=tokenizer.eos_token_id,
91
  )[0]["generated_text"]
 
 
92
  return {"response": result}
93
 
94
 
95
- # === Run (opsional) ===
96
  if __name__ == "__main__":
97
  uvicorn.run("app:app", host="0.0.0.0", port=8000)
 
1
  from fastapi import FastAPI, UploadFile, File
2
  from fastapi.middleware.cors import CORSMiddleware
3
+ from transformers import pipeline, AutoTokenizer
 
4
  from PIL import Image
5
  import numpy as np
6
  import uvicorn
7
  from tensorflow.keras.models import load_model
 
8
  import os
9
+ import hashlib
10
+ import diskcache
11
+ import json
12
 
13
  # === Inisialisasi FastAPI ===
14
  app = FastAPI()
15
 
16
+ # === CORS ===
17
  app.add_middleware(
18
  CORSMiddleware,
19
  allow_origins=["*"],
 
22
  allow_headers=["*"],
23
  )
24
 
25
+ # === Inisialisasi Cache ===
26
+ cache = diskcache.Cache("/tmp/cache")
27
+
28
+ # === Load Model Gambar ===
29
+ model_path = os.path.join(
30
+ os.path.dirname(__file__), "saved_model", "multidisease_model.h5"
31
+ )
32
  if not os.path.exists(model_path):
33
  raise FileNotFoundError(f"Model tidak ditemukan di path: {model_path}")
34
  image_model = load_model(model_path)
35
 
 
 
36
  label_map = {
37
  0: "BacterialBlight",
38
  1: "Blast",
 
50
  "Tungro": "Penyakit virus yang membuat daun menguning dan pertumbuhan terhambat.",
51
  }
52
 
53
+ # === Load Chatbot ===
54
  chatbot = pipeline(
55
  "text-generation",
56
  model="ARusDian/AgroLens-Chatbot",
 
59
 
60
 
61
  def preprocess_image(image: Image.Image):
62
+ image = image.resize((224, 224))
63
+ img_array = np.array(image) / 255.0
64
+ img_array = np.expand_dims(img_array, axis=0)
65
  return img_array
66
 
67
 
68
+ def hash_image(image: Image.Image) -> str:
69
+ """Generate hash for image content."""
70
+ image_bytes = image.tobytes()
71
+ return hashlib.md5(image_bytes).hexdigest()
72
+
73
+
74
+ # === Endpoint: Prediksi Gambar ===
75
  @app.post("/predict-image")
76
  async def predict_image(file: UploadFile = File(...)):
77
  image = Image.open(file.file).convert("RGB")
78
+ image_hash = hash_image(image)
79
+
80
+ if image_hash in cache:
81
+ return cache[image_hash]
82
 
83
+ input_tensor = preprocess_image(image)
84
  pred = np.argmax(image_model.predict(input_tensor), axis=1)[0]
85
  label = label_map.get(pred, "Tidak dikenal")
86
  description = label_descriptions.get(label, "-")
87
 
88
+ result = {"prediction": label, "description": description}
89
+ cache[image_hash] = result
90
+ return result
91
 
92
 
93
+ # === Endpoint: Chatbot ===
94
  @app.post("/chatbot")
95
  async def describe(prompt: dict):
96
  text = prompt["prompt"]
97
+ key = hashlib.md5(text.encode()).hexdigest()
98
+
99
+ if key in cache:
100
+ return {"response": cache[key]}
101
+
102
  tokenizer = AutoTokenizer.from_pretrained("ARusDian/AgroLens-Chatbot")
103
  result = chatbot(
104
  text,
 
110
  do_sample=True,
111
  eos_token_id=tokenizer.eos_token_id,
112
  )[0]["generated_text"]
113
+
114
+ cache[key] = result
115
  return {"response": result}
116
 
117
 
118
+ # === Run lokal (tidak dipakai di Spaces) ===
119
  if __name__ == "__main__":
120
  uvicorn.run("app:app", host="0.0.0.0", port=8000)