ReactLover commited on
Commit
0b3d9fc
·
verified ·
1 Parent(s): 7c4ca02

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -11
app.py CHANGED
@@ -4,18 +4,18 @@ from transformers import pipeline
4
  from PIL import Image
5
  import io, os, traceback
6
 
7
- # Make sure Hugging Face cache is writable
8
  os.environ["HF_HOME"] = "/app/cache"
9
  os.environ["TRANSFORMERS_CACHE"] = "/app/cache"
10
  os.environ["HF_HUB_CACHE"] = "/app/cache/hub"
11
 
12
  app = FastAPI()
13
 
14
- # Load SmolVLM with the pipeline API
15
  pipe = pipeline(
16
  "image-to-text",
17
  model="HuggingFaceTB/SmolVLM-256M-Instruct",
18
- device=-1 # CPU for free tier
19
  )
20
 
21
  @app.get("/")
@@ -45,16 +45,22 @@ async def predict_gender(file: UploadFile = File(...)):
45
  image_bytes = await file.read()
46
  image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
47
 
48
- # Instruction for the model
49
- prompt = "Is the person on this ID male or female?"
 
50
 
51
- # Run model (pipeline handles image + prompt via generate_kwargs)
52
- result = pipe(image, generate_kwargs={"max_new_tokens": 32, "prompt": prompt})
 
 
 
 
 
53
 
54
- # Extract model output
55
- answer = result[0]["generated_text"].strip()
56
-
57
- return JSONResponse({"gender": answer})
58
 
59
  except Exception as e:
60
  traceback.print_exc()
 
4
  from PIL import Image
5
  import io, os, traceback
6
 
7
+ # Cache settings
8
  os.environ["HF_HOME"] = "/app/cache"
9
  os.environ["TRANSFORMERS_CACHE"] = "/app/cache"
10
  os.environ["HF_HUB_CACHE"] = "/app/cache/hub"
11
 
12
  app = FastAPI()
13
 
14
+ # Load SmolVLM as pure image-to-text
15
  pipe = pipeline(
16
  "image-to-text",
17
  model="HuggingFaceTB/SmolVLM-256M-Instruct",
18
+ device=-1 # CPU
19
  )
20
 
21
  @app.get("/")
 
45
  image_bytes = await file.read()
46
  image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
47
 
48
+ # Run the model (image only)
49
+ result = pipe(image, max_new_tokens=32)
50
+ caption = result[0]["generated_text"].strip()
51
 
52
+ # Very simple heuristic: check for male/female in caption
53
+ gender = "unknown"
54
+ lower_caption = caption.lower()
55
+ if "male" in lower_caption or "man" in lower_caption:
56
+ gender = "male"
57
+ elif "female" in lower_caption or "woman" in lower_caption:
58
+ gender = "female"
59
 
60
+ return JSONResponse({
61
+ "caption": caption,
62
+ "gender": gender
63
+ })
64
 
65
  except Exception as e:
66
  traceback.print_exc()