allfahad commited on
Commit
419df97
·
verified ·
1 Parent(s): d1cafde

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -19
app.py CHANGED
@@ -1,4 +1,3 @@
1
- # app.py
2
  from fastapi import FastAPI, File, UploadFile
3
  from transformers import pipeline
4
  from PIL import Image
@@ -6,39 +5,33 @@ import io
6
 
7
  app = FastAPI()
8
 
9
- # Load the model pipeline only once when the Space starts.
10
- # This makes it ready for all incoming requests.
11
  classifier = pipeline("zero-shot-image-classification",
12
- model="google/vit-base-patch16-224",
13
- device=-1) # -1 forces the model to use the CPU
14
 
15
  @app.get("/")
16
- def root():
17
  return {"message": "Fish Detector API is running. Use POST /detect"}
18
 
19
  @app.post("/detect")
20
  async def detect(file: UploadFile = File(...)):
21
- # 1. Read and open the image from the uploaded file
22
  contents = await file.read()
23
  image = Image.open(io.BytesIO(contents)).convert("RGB")
24
 
25
- # 2. Define the labels for zero-shot classification.
26
- # These are the categories our model will choose from.
27
  candidate_labels = [
28
- "a photo of a fish, with fins and scales",
29
- "a photo of a person, an animal, or an object that is not a fish",
30
- "an empty photo with no fish in it"
31
  ]
32
 
33
- # 3. Run the image through the pipeline to get predictions
34
  predictions = classifier(image, candidate_labels=candidate_labels)
35
 
36
- # 4. The top prediction is the one with the highest score.
37
- # We check if its label is the fish-related one.
38
- is_fish = predictions[0]['label'] == candidate_labels[0]
39
-
40
- # 5. Return the result as a plain text string
41
- if is_fish:
42
  return "fish"
43
  else:
44
  return "not a fish"
 
 
1
  from fastapi import FastAPI, File, UploadFile
2
  from transformers import pipeline
3
  from PIL import Image
 
5
 
6
  app = FastAPI()
7
 
8
+ # Load the lightweight zero‑shot image classification model
9
+ # `device=-1` forces the model to run on the CPU
10
  classifier = pipeline("zero-shot-image-classification",
11
+ model="sachin/tiny_clip",
12
+ device=-1)
13
 
14
  @app.get("/")
15
+ def read_root():
16
  return {"message": "Fish Detector API is running. Use POST /detect"}
17
 
18
  @app.post("/detect")
19
  async def detect(file: UploadFile = File(...)):
20
+ # 1. Read and open the uploaded image
21
  contents = await file.read()
22
  image = Image.open(io.BytesIO(contents)).convert("RGB")
23
 
24
+ # 2. Define the two possible labels for the model to choose from
 
25
  candidate_labels = [
26
+ "a photo of a fish",
27
+ "a photo that does not contain a fish"
 
28
  ]
29
 
30
+ # 3. Run the zero‑shot classifier
31
  predictions = classifier(image, candidate_labels=candidate_labels)
32
 
33
+ # 4. The top prediction is the one with the highest score
34
+ if predictions[0]['label'] == "a photo of a fish":
 
 
 
 
35
  return "fish"
36
  else:
37
  return "not a fish"