import torch import re import gradio as gr from transformers import AutoTokenizer, ViTFeatureExtractor, AutoModel device='cpu' encoder_checkpoint = "Thibalte/captionning_project" feature_extractor = ViTFeatureExtractor.from_pretrained(encoder_checkpoint) tokenizer = AutoTokenizer.from_pretrained("Thibalte/captionning_project") model = AutoModel.from_pretrained("Thibalte/captionning_project") def predict(image,max_length=24, num_beams=4): image = image.convert('RGB') image = feature_extractor(image, return_tensors="pt").pixel_values.to(device) clean_text = lambda x: x.replace('<|endoftext|>','').split('\n')[0] caption_ids = model.generate(image, max_length = max_length)[0] caption_text = clean_text(tokenizer.decode(caption_ids)) return caption_text # Gradio Interface gradio_app = gr.Interface( fn=predict, inputs=gr.Image(label="Select image for captioning", sources=['upload', 'webcam'], type="pil"), outputs=[gr.Textbox(label="Image Caption")], examples = [f"example{i}.jpg" for i in range(1,7)], title="Image Captioning with our model", ) if __name__ == "__main__": gradio_app.launch()