rajkhanke commited on
Commit
f475440
·
verified ·
1 Parent(s): 29ff203

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -14
app.py CHANGED
@@ -1,9 +1,11 @@
1
- from fastapi import FastAPI, File, UploadFile, HTTPException
2
  from fastapi.responses import JSONResponse
3
  from tensorflow.keras.models import load_model
4
  from PIL import Image
5
  import numpy as np
6
  import requests
 
 
7
 
8
  # Initialize FastAPI app
9
  app = FastAPI()
@@ -19,7 +21,7 @@ breed_names = {
19
  }
20
 
21
  # Function to preprocess the image
22
- def preprocess_image(image):
23
  image = image.resize((150, 150))
24
  img_array = np.array(image)
25
  img_array = img_array / 255.0
@@ -27,14 +29,14 @@ def preprocess_image(image):
27
  return img_array
28
 
29
  # Function to classify the breed
30
- def classify_breed(image, model):
31
  img_array = preprocess_image(image)
32
  predictions = model.predict(img_array)
33
  predicted_class_index = np.argmax(predictions)
34
- return breed_names[predicted_class_index]
35
 
36
  # Function to fetch breed information from an API
37
- def fetch_breed_info(breed_name):
38
  url = f'https://api.thedogapi.com/v1/breeds/search?q={breed_name}'
39
  response = requests.get(url)
40
  if response.status_code == 200:
@@ -45,14 +47,25 @@ def fetch_breed_info(breed_name):
45
 
46
  # API route for prediction
47
  @app.post("/predict")
48
- async def predict(file: UploadFile = File(...)):
 
 
 
49
  try:
50
- # Check file type
51
- if file.content_type not in ["image/jpeg", "image/png", "image/jpg"]:
52
- raise HTTPException(status_code=400, detail="Invalid file type. Only JPG and PNG are allowed.")
53
-
54
- # Read and process the image
55
- image = Image.open(file.file)
 
 
 
 
 
 
 
 
56
 
57
  # Classify the breed
58
  breed_name = classify_breed(image, model)
@@ -63,7 +76,7 @@ async def predict(file: UploadFile = File(...)):
63
  # Prepare response
64
  response = {
65
  "predicted_breed": breed_name,
66
- "breed_info": breed_info[0] if breed_info else "No additional information available."
67
  }
68
  return JSONResponse(content=response)
69
 
@@ -73,4 +86,4 @@ async def predict(file: UploadFile = File(...)):
73
  # Root route
74
  @app.get("/")
75
  def read_root():
76
- return {"message": "Welcome to the Dog Breed Classification API!"}
 
1
+ from fastapi import FastAPI, File, UploadFile, HTTPException, Query
2
  from fastapi.responses import JSONResponse
3
  from tensorflow.keras.models import load_model
4
  from PIL import Image
5
  import numpy as np
6
  import requests
7
+ import io
8
+ from typing import Optional
9
 
10
  # Initialize FastAPI app
11
  app = FastAPI()
 
21
  }
22
 
23
  # Function to preprocess the image
24
+ def preprocess_image(image: Image.Image):
25
  image = image.resize((150, 150))
26
  img_array = np.array(image)
27
  img_array = img_array / 255.0
 
29
  return img_array
30
 
31
  # Function to classify the breed
32
+ def classify_breed(image: Image.Image, model):
33
  img_array = preprocess_image(image)
34
  predictions = model.predict(img_array)
35
  predicted_class_index = np.argmax(predictions)
36
+ return breed_names.get(predicted_class_index, "Unknown")
37
 
38
  # Function to fetch breed information from an API
39
+ def fetch_breed_info(breed_name: str):
40
  url = f'https://api.thedogapi.com/v1/breeds/search?q={breed_name}'
41
  response = requests.get(url)
42
  if response.status_code == 200:
 
47
 
48
  # API route for prediction
49
  @app.post("/predict")
50
+ async def predict(
51
+ file: Optional[UploadFile] = File(None),
52
+ url: Optional[str] = Query(None, description="Public URL of the image")
53
+ ):
54
  try:
55
+ # Determine input method: file has priority over URL.
56
+ if file is not None:
57
+ # Check file type
58
+ if file.content_type not in ["image/jpeg", "image/png", "image/jpg"]:
59
+ raise HTTPException(status_code=400, detail="Invalid file type. Only JPG and PNG are allowed.")
60
+ image = Image.open(file.file)
61
+ elif url is not None:
62
+ # Download image from URL
63
+ resp = requests.get(url)
64
+ if resp.status_code != 200:
65
+ raise HTTPException(status_code=400, detail="Unable to fetch image from provided URL.")
66
+ image = Image.open(io.BytesIO(resp.content))
67
+ else:
68
+ raise HTTPException(status_code=400, detail="No image provided. Please upload a file or provide a URL.")
69
 
70
  # Classify the breed
71
  breed_name = classify_breed(image, model)
 
76
  # Prepare response
77
  response = {
78
  "predicted_breed": breed_name,
79
+ "breed_info": breed_info[0] if breed_info and len(breed_info) > 0 else "No additional information available."
80
  }
81
  return JSONResponse(content=response)
82
 
 
86
  # Root route
87
  @app.get("/")
88
  def read_root():
89
+ return {"message": "Welcome to the Dog Breed Classification API!"}