Hug0endob commited on
Commit
71b45b9
·
verified ·
1 Parent(s): b89f943

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -0
app.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoProcessor, LlavaForConditionalGeneration
3
+ import gradio as gr
4
+ from PIL import Image
5
+ import requests
6
+
7
+ # -------------------------------------------------
8
+ # Model identifier (replace if you fork or use a different checkpoint)
9
+ # -------------------------------------------------
10
+ MODEL_NAME = "fpgaminer/joycaption-llama3.1-8b" # 8‑B checkpoint fits comfortably on CPU
11
+
12
+ # -------------------------------------------------
13
+ # Load processor and model (CPU only)
14
+ # -------------------------------------------------
15
+ processor = AutoProcessor.from_pretrained(MODEL_NAME)
16
+
17
+ # `device_map="cpu"` forces everything onto the CPU
18
+ llava_model = LlavaForConditionalGeneration.from_pretrained(
19
+ MODEL_NAME,
20
+ device_map="cpu",
21
+ torch_dtype=torch.bfloat16, # native dtype for this model
22
+ )
23
+
24
+ llava_model.eval()
25
+
26
+ # -------------------------------------------------
27
+ # Inference function used by Gradio
28
+ # -------------------------------------------------
29
+ def generate_caption(image: Image.Image, prompt: str = "Describe the image.") -> str:
30
+ # Prepare inputs for the model
31
+ inputs = processor(images=image, text=prompt, return_tensors="pt")
32
+ inputs = {k: v.to(llava_model.device) for k, v in inputs.items()}
33
+
34
+ # Generate up to 64 new tokens (adjust if you want longer captions)
35
+ with torch.no_grad():
36
+ output_ids = llava_model.generate(**inputs, max_new_tokens=64)
37
+
38
+ # Decode to plain text
39
+ caption = processor.decode(output_ids[0], skip_special_tokens=True)
40
+ return caption
41
+
42
+ # -------------------------------------------------
43
+ # Gradio UI
44
+ # -------------------------------------------------
45
+ iface = gr.Interface(
46
+ fn=generate_caption,
47
+ inputs=[
48
+ gr.Image(type="pil", label="Upload an image"),
49
+ gr.Textbox(label="Prompt (optional)", value="Describe the image.")
50
+ ],
51
+ outputs=gr.Textbox(label="Generated caption"),
52
+ title="JoyCaption (CPU‑only) Demo",
53
+ description="Upload an image and let the JoyCaption model generate a caption. Runs entirely on the free CPU tier.",
54
+ allow_flagging="never"
55
+ )
56
+
57
+ if __name__ == "__main__":
58
+ iface.launch()