AnkitS1997 commited on
Commit
177e69b
1 Parent(s): e04674a

added exception handling

Browse files
.ipynb_checkpoints/app-checkpoint.py CHANGED
@@ -1,6 +1,6 @@
1
- from fastapi import FastAPI, File, UploadFile
2
  from fastapi.middleware.cors import CORSMiddleware
3
- from PIL import Image
4
  from transformers import AutoProcessor, Blip2ForConditionalGeneration
5
  import torch
6
  import io
@@ -9,26 +9,41 @@ app = FastAPI()
9
 
10
  app.add_middleware(
11
  CORSMiddleware,
12
- allow_origins=["*"], # Adjust this as needed for security
13
  allow_credentials=True,
14
  allow_methods=["*"],
15
  allow_headers=["*"],
16
  )
17
 
18
  # Load the model and processor
19
- model = Blip2ForConditionalGeneration.from_pretrained("ybelkada/blip2-opt-2.7b-fp16-sharded")
20
- model.load_adapter('blip-cpu-model')
21
- processor = AutoProcessor.from_pretrained("Salesforce/blip2-opt-2.7b")
22
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
23
- model.to(device)
 
 
 
24
 
25
  @app.post("/generate-caption/")
26
  async def generate_caption(file: UploadFile = File(...)):
27
- image = Image.open(io.BytesIO(await file.read()))
28
- inputs = processor(images=image, return_tensors="pt").to(device, torch.float16)
 
 
 
 
 
 
29
 
30
- with torch.no_grad():
31
- caption_ids = model.generate(**inputs, max_length=128)
32
- caption = processor.decode(caption_ids[0], skip_special_tokens=True)
33
-
34
- return {"caption": caption}
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
+ from PIL import Image, UnidentifiedImageError
4
  from transformers import AutoProcessor, Blip2ForConditionalGeneration
5
  import torch
6
  import io
 
9
 
10
  app.add_middleware(
11
  CORSMiddleware,
12
+ allow_origins=["*"],
13
  allow_credentials=True,
14
  allow_methods=["*"],
15
  allow_headers=["*"],
16
  )
17
 
18
  # Load the model and processor
19
+ try:
20
+ model = Blip2ForConditionalGeneration.from_pretrained("ybelkada/blip2-opt-2.7b-fp16-sharded")
21
+ model.load_adapter('blip-cpu-model')
22
+ processor = AutoProcessor.from_pretrained("Salesforce/blip2-opt-2.7b")
23
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
24
+ model.to(device)
25
+ except Exception as e:
26
+ raise RuntimeError(f"Failed to load the model or processor: {str(e)}")
27
 
28
  @app.post("/generate-caption/")
29
  async def generate_caption(file: UploadFile = File(...)):
30
+ try:
31
+ image = Image.open(io.BytesIO(await file.read()))
32
+ except UnidentifiedImageError:
33
+ # Raise a 400 error if the file is not a valid image
34
+ raise HTTPException(status_code=400, detail="Uploaded file is not a valid image.")
35
+ except Exception as e:
36
+ # Catch any other unexpected errors related to image processing
37
+ raise HTTPException(status_code=500, detail=f"An unexpected error occurred while processing the image: {str(e)}")
38
 
39
+ try:
40
+ inputs = processor(images=image, return_tensors="pt").to(device, torch.float16)
41
+
42
+ with torch.no_grad():
43
+ caption_ids = model.generate(**inputs, max_length=128)
44
+ caption = processor.decode(caption_ids[0], skip_special_tokens=True)
45
+
46
+ return {"caption": caption}
47
+ except Exception as e:
48
+ # Catch any errors during the caption generation process
49
+ raise HTTPException(status_code=500, detail=f"An error occurred while generating the caption: {str(e)}")
.ipynb_checkpoints/streamlit_app-checkpoint.py CHANGED
@@ -1,41 +1,38 @@
1
  import streamlit as st
2
  import requests
3
- from PIL import Image
4
  from transformers import AutoProcessor, Blip2ForConditionalGeneration
5
  import torch
6
  import io
7
 
8
 
9
- # @st.cache_resource
10
- # def load_model():
11
- # model = Blip2ForConditionalGeneration.from_pretrained("ybelkada/blip2-opt-2.7b-fp16-sharded")
12
- # model.load_adapter('blip-cpu-model')
13
- # processor = AutoProcessor.from_pretrained("Salesforce/blip2-opt-2.7b")
14
- # device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
15
- # model.to(device)
16
- # return model, processor
17
-
18
- # model, processor = load_model()
19
- # device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
20
-
21
  st.title("Image Captioning with Fine-Tuned BLiPv2 Model")
22
 
23
  uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
24
 
25
  if uploaded_file is not None:
26
- image = Image.open(uploaded_file)
27
- st.image(image, caption="Uploaded Image", use_column_width=True)
28
-
29
- files = {"file": uploaded_file.getvalue()}
30
- print("Sending API request")
31
- response = requests.post("http://0.0.0.0:8502/generate-caption/", files=files)
32
- caption = response.json().get("caption")
33
-
34
- # inputs = processor(images=image, return_tensors="pt").to(device, torch.float16)
35
-
36
- # with torch.no_grad():
37
- # caption_ids = model.generate(**inputs, max_length=128)
38
- # caption = processor.decode(caption_ids[0], skip_special_tokens=True)
39
-
40
- st.write("Generated Caption:")
41
- st.write(f"**{caption}**")
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import requests
3
+ from PIL import Image, UnidentifiedImageError
4
  from transformers import AutoProcessor, Blip2ForConditionalGeneration
5
  import torch
6
  import io
7
 
8
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  st.title("Image Captioning with Fine-Tuned BLiPv2 Model")
10
 
11
  uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
12
 
13
  if uploaded_file is not None:
14
+ try:
15
+ image = Image.open(uploaded_file)
16
+ st.image(image, caption="Uploaded Image", use_column_width=True)
17
+
18
+ try:
19
+ files = {"file": uploaded_file.getvalue()}
20
+ print("Sending API request")
21
+ response = requests.post("http://0.0.0.0:8502/generate-caption/", files=files)
22
+ caption = response.json().get("caption")
23
+ except requests.exceptions.RequestException as e:
24
+ st.error(f"An error occurred while making the API request: {str(e)}")
25
+ caption = "Error generating caption"
26
+ except ValueError as e:
27
+ st.error(f"An error occurred while parsing the API response: {str(e)}")
28
+ caption = "Error generating caption"
29
+
30
+ st.write("Generated Caption:")
31
+ st.write(f"**{caption}**")
32
+
33
+ except UnidentifiedImageError:
34
+ st.error("The uploaded file is not a valid image. Please upload a JPG, JPEG, or PNG file.")
35
+ except Exception as e:
36
+ st.error(f"An unexpected error occurred: {str(e)}")
37
+ else:
38
+ st.write("Please upload an image to generate a caption.")
app.py CHANGED
@@ -1,6 +1,6 @@
1
- from fastapi import FastAPI, File, UploadFile
2
  from fastapi.middleware.cors import CORSMiddleware
3
- from PIL import Image
4
  from transformers import AutoProcessor, Blip2ForConditionalGeneration
5
  import torch
6
  import io
@@ -9,26 +9,41 @@ app = FastAPI()
9
 
10
  app.add_middleware(
11
  CORSMiddleware,
12
- allow_origins=["*"], # Adjust this as needed for security
13
  allow_credentials=True,
14
  allow_methods=["*"],
15
  allow_headers=["*"],
16
  )
17
 
18
  # Load the model and processor
19
- model = Blip2ForConditionalGeneration.from_pretrained("ybelkada/blip2-opt-2.7b-fp16-sharded")
20
- model.load_adapter('blip-cpu-model')
21
- processor = AutoProcessor.from_pretrained("Salesforce/blip2-opt-2.7b")
22
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
23
- model.to(device)
 
 
 
24
 
25
  @app.post("/generate-caption/")
26
  async def generate_caption(file: UploadFile = File(...)):
27
- image = Image.open(io.BytesIO(await file.read()))
28
- inputs = processor(images=image, return_tensors="pt").to(device, torch.float16)
 
 
 
 
 
 
29
 
30
- with torch.no_grad():
31
- caption_ids = model.generate(**inputs, max_length=128)
32
- caption = processor.decode(caption_ids[0], skip_special_tokens=True)
33
-
34
- return {"caption": caption}
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
+ from PIL import Image, UnidentifiedImageError
4
  from transformers import AutoProcessor, Blip2ForConditionalGeneration
5
  import torch
6
  import io
 
9
 
10
  app.add_middleware(
11
  CORSMiddleware,
12
+ allow_origins=["*"],
13
  allow_credentials=True,
14
  allow_methods=["*"],
15
  allow_headers=["*"],
16
  )
17
 
18
  # Load the model and processor
19
+ try:
20
+ model = Blip2ForConditionalGeneration.from_pretrained("ybelkada/blip2-opt-2.7b-fp16-sharded")
21
+ model.load_adapter('blip-cpu-model')
22
+ processor = AutoProcessor.from_pretrained("Salesforce/blip2-opt-2.7b")
23
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
24
+ model.to(device)
25
+ except Exception as e:
26
+ raise RuntimeError(f"Failed to load the model or processor: {str(e)}")
27
 
28
  @app.post("/generate-caption/")
29
  async def generate_caption(file: UploadFile = File(...)):
30
+ try:
31
+ image = Image.open(io.BytesIO(await file.read()))
32
+ except UnidentifiedImageError:
33
+ # Raise a 400 error if the file is not a valid image
34
+ raise HTTPException(status_code=400, detail="Uploaded file is not a valid image.")
35
+ except Exception as e:
36
+ # Catch any other unexpected errors related to image processing
37
+ raise HTTPException(status_code=500, detail=f"An unexpected error occurred while processing the image: {str(e)}")
38
 
39
+ try:
40
+ inputs = processor(images=image, return_tensors="pt").to(device, torch.float16)
41
+
42
+ with torch.no_grad():
43
+ caption_ids = model.generate(**inputs, max_length=128)
44
+ caption = processor.decode(caption_ids[0], skip_special_tokens=True)
45
+
46
+ return {"caption": caption}
47
+ except Exception as e:
48
+ # Catch any errors during the caption generation process
49
+ raise HTTPException(status_code=500, detail=f"An error occurred while generating the caption: {str(e)}")
streamlit_app.py CHANGED
@@ -1,41 +1,38 @@
1
  import streamlit as st
2
  import requests
3
- from PIL import Image
4
  from transformers import AutoProcessor, Blip2ForConditionalGeneration
5
  import torch
6
  import io
7
 
8
 
9
- # @st.cache_resource
10
- # def load_model():
11
- # model = Blip2ForConditionalGeneration.from_pretrained("ybelkada/blip2-opt-2.7b-fp16-sharded")
12
- # model.load_adapter('blip-cpu-model')
13
- # processor = AutoProcessor.from_pretrained("Salesforce/blip2-opt-2.7b")
14
- # device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
15
- # model.to(device)
16
- # return model, processor
17
-
18
- # model, processor = load_model()
19
- # device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
20
-
21
  st.title("Image Captioning with Fine-Tuned BLiPv2 Model")
22
 
23
  uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
24
 
25
  if uploaded_file is not None:
26
- image = Image.open(uploaded_file)
27
- st.image(image, caption="Uploaded Image", use_column_width=True)
28
-
29
- files = {"file": uploaded_file.getvalue()}
30
- print("Sending API request")
31
- response = requests.post("http://0.0.0.0:8502/generate-caption/", files=files)
32
- caption = response.json().get("caption")
33
-
34
- # inputs = processor(images=image, return_tensors="pt").to(device, torch.float16)
35
-
36
- # with torch.no_grad():
37
- # caption_ids = model.generate(**inputs, max_length=128)
38
- # caption = processor.decode(caption_ids[0], skip_special_tokens=True)
39
-
40
- st.write("Generated Caption:")
41
- st.write(f"**{caption}**")
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import requests
3
+ from PIL import Image, UnidentifiedImageError
4
  from transformers import AutoProcessor, Blip2ForConditionalGeneration
5
  import torch
6
  import io
7
 
8
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  st.title("Image Captioning with Fine-Tuned BLiPv2 Model")
10
 
11
  uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
12
 
13
  if uploaded_file is not None:
14
+ try:
15
+ image = Image.open(uploaded_file)
16
+ st.image(image, caption="Uploaded Image", use_column_width=True)
17
+
18
+ try:
19
+ files = {"file": uploaded_file.getvalue()}
20
+ print("Sending API request")
21
+ response = requests.post("http://0.0.0.0:8502/generate-caption/", files=files)
22
+ caption = response.json().get("caption")
23
+ except requests.exceptions.RequestException as e:
24
+ st.error(f"An error occurred while making the API request: {str(e)}")
25
+ caption = "Error generating caption"
26
+ except ValueError as e:
27
+ st.error(f"An error occurred while parsing the API response: {str(e)}")
28
+ caption = "Error generating caption"
29
+
30
+ st.write("Generated Caption:")
31
+ st.write(f"**{caption}**")
32
+
33
+ except UnidentifiedImageError:
34
+ st.error("The uploaded file is not a valid image. Please upload a JPG, JPEG, or PNG file.")
35
+ except Exception as e:
36
+ st.error(f"An unexpected error occurred: {str(e)}")
37
+ else:
38
+ st.write("Please upload an image to generate a caption.")