ABDRauf commited on
Commit
67434ff
Β·
verified Β·
1 Parent(s): caf813e

fixed errors

Browse files
Files changed (1) hide show
  1. app.py +20 -28
app.py CHANGED
@@ -1,21 +1,20 @@
1
- from transformers import BlipProcessor, BlipForConditionalGeneration # For image captioning using BLIP model
2
  import io
3
  from PIL import Image
4
  from fastapi import FastAPI, File, UploadFile, HTTPException
5
  from fastapi.responses import JSONResponse
6
- import uvicorn
7
- import torch # For running deep learning models (PyTorch backend)
8
 
9
- # Load BLIP (Bootstrapping Language-Image Pretraining) model
10
  processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
11
  model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
12
 
13
-
14
-
15
-
16
- def image_to_speech(image):
17
  # Step 1: Generate a more detailed caption
 
18
  inputs = processor(image, return_tensors="pt")
 
19
  out = model.generate(
20
  **inputs,
21
  max_length=90, # Allow longer, more detailed sentences
@@ -25,55 +24,48 @@ def image_to_speech(image):
25
  early_stopping=True
26
  )
27
  caption = processor.decode(out[0], skip_special_tokens=True)
 
28
 
29
- return caption,
30
-
31
- # ── FastAPI app ────────────────────────────────────────────────────────────────
32
  app = FastAPI(
33
  title="VocalEyes API",
34
- description="Converts an uploaded image into a short scene description via RelTR + T5.",
35
  version="1.0.0",
36
  )
37
 
38
-
39
  @app.get("/")
40
  def root():
41
  return {"status": "ok", "message": "VocalEyes API is running. POST an image to /predict"}
42
 
43
-
44
  @app.post("/predict")
45
  async def predict(file: UploadFile = File(...)):
46
- # ── Validate content type ──────────────────────────────────────────────────
47
  if file.content_type not in ("image/jpeg", "image/png", "image/webp", "image/bmp"):
48
  raise HTTPException(
49
  status_code=415,
50
  detail=f"Unsupported file type '{file.content_type}'. Send JPEG, PNG, WEBP, or BMP.",
51
  )
52
-
53
- # ── Read & preprocess ──────────────────────────────────────────────────────
54
  try:
55
  raw = await file.read()
56
  image = Image.open(io.BytesIO(raw)).convert("RGB")
57
  except Exception as e:
58
  raise HTTPException(status_code=400, detail=f"Could not read image: {e}")
59
 
60
- img_tensor = transform(image).unsqueeze(0) # (1, 3, H, W)
61
-
62
- # ── Run pipeline ───────────────────────────────────────────────────────────
63
  try:
64
- result = image_to_speech(img_tensor)
 
65
  except Exception as e:
66
  raise HTTPException(status_code=500, detail=f"Pipeline error: {e}")
67
 
 
68
  return JSONResponse({
69
- "description": result["generated_text"],
70
- "triplets": [
71
- {"subject": s, "relation": r, "object": o}
72
- for s, r, o in result["triplets"]
73
- ],
74
  })
75
 
76
-
77
- # ── Entry point ────────────────────────────────────────────────────────────────
78
  if __name__ == "__main__":
 
79
  uvicorn.run("app:app", host="0.0.0.0", port=7860)
 
1
+ from transformers import BlipProcessor, BlipForConditionalGeneration
2
  import io
3
  from PIL import Image
4
  from fastapi import FastAPI, File, UploadFile, HTTPException
5
  from fastapi.responses import JSONResponse
6
+ import uvicorn
7
+ import torch
8
 
9
+ # ── Load BLIP Model ────────────────────────────────────────────────────────
10
  processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
11
  model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
12
 
13
+ def image_to_speech(image: Image.Image) -> str:
 
 
 
14
  # Step 1: Generate a more detailed caption
15
+ # The processor handles the conversion from PIL Image to PyTorch tensors
16
  inputs = processor(image, return_tensors="pt")
17
+
18
  out = model.generate(
19
  **inputs,
20
  max_length=90, # Allow longer, more detailed sentences
 
24
  early_stopping=True
25
  )
26
  caption = processor.decode(out[0], skip_special_tokens=True)
27
+ return caption # Removed the trailing comma
28
 
29
+ # ── FastAPI app ────────────────────────────────────────────────────────────
 
 
30
  app = FastAPI(
31
  title="VocalEyes API",
32
+ description="Converts an uploaded image into a short scene description via BLIP.",
33
  version="1.0.0",
34
  )
35
 
 
36
  @app.get("/")
37
  def root():
38
  return {"status": "ok", "message": "VocalEyes API is running. POST an image to /predict"}
39
 
 
40
  @app.post("/predict")
41
  async def predict(file: UploadFile = File(...)):
42
+ # ── Validate content type ──────────────────────────────────────────────
43
  if file.content_type not in ("image/jpeg", "image/png", "image/webp", "image/bmp"):
44
  raise HTTPException(
45
  status_code=415,
46
  detail=f"Unsupported file type '{file.content_type}'. Send JPEG, PNG, WEBP, or BMP.",
47
  )
48
+
49
+ # ── Read & preprocess ──────────────────────────────────────────────────
50
  try:
51
  raw = await file.read()
52
  image = Image.open(io.BytesIO(raw)).convert("RGB")
53
  except Exception as e:
54
  raise HTTPException(status_code=400, detail=f"Could not read image: {e}")
55
 
56
+ # ── Run pipeline ───────────────────────────────────────────────────────
 
 
57
  try:
58
+ # Pass the PIL Image directly to our BLIP function
59
+ caption = image_to_speech(image)
60
  except Exception as e:
61
  raise HTTPException(status_code=500, detail=f"Pipeline error: {e}")
62
 
63
+ # Return the clean description
64
  return JSONResponse({
65
+ "description": caption
 
 
 
 
66
  })
67
 
68
+ # ── Entry point ──────────────────────────────────────────────────���─────────
 
69
  if __name__ == "__main__":
70
+ # Make sure this file is saved as app.py if you are passing "app:app"
71
  uvicorn.run("app:app", host="0.0.0.0", port=7860)