File size: 2,102 Bytes
2434931
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from transformers import AutoProcessor, AutoModelForCausalLM, AutoConfig
import gradio as gr
import torch

# # Load the processor and model
processor = AutoProcessor.from_pretrained("microsoft/git-base")
# config = AutoConfig.from_pretrained("./adapter_config.json")
# # model = AutoModelForCausalLM.from_pretrained("microsoft/git-base")

# model_path = "./adapter_model.safetensors"
# model = AutoModelForCausalLM.from_pretrained(model_path)

from transformers import AutoModelForCausalLM
from peft import PeftModel

#Base model on your local filesystem
base_model_dir = "microsoft/git-base"
base_model = AutoModelForCausalLM.from_pretrained(base_model_dir)

#Adaptor directory on your local filesystem
adaptor_dir = "./"
merged_model = PeftModel.from_pretrained(base_model,adaptor_dir)

merged_model = merged_model.merge_and_unload()
merged_model.save_pretrained("./Merged-Model/")

model = merged_model


def predict(image):
    try:
        # Prepare the image using the processor
        inputs = processor(images=image, return_tensors="pt")

        # Move inputs to the appropriate device
        device = "cuda" if torch.cuda.is_available() else "cpu"
        inputs = {key: value.to(device) for key, value in inputs.items()}
        model.to(device)

        # Generate the caption
        outputs = model.generate(**inputs)

        # Decode the generated caption
        caption = processor.batch_decode(outputs, skip_special_tokens=True)[0]

        return caption

    except Exception as e:
        print("Error during prediction:", str(e))
        return "Error: " + str(e)

# https://www.gradio.app/guides
with gr.Blocks() as demo:
    image = gr.Image(type="pil")
    predict_btn = gr.Button("Predict", variant="primary")
    output = gr.Label(label="Generated Caption")

    inputs = [image]
    outputs = [output]

    predict_btn.click(predict, inputs=inputs, outputs=outputs)

if __name__ == "__main__":
    demo.launch()  # Local machine only
    # demo.launch(server_name="0.0.0.0")  # LAN access to local machine
    # demo.launch(share=True)  # Public access to local machine