import gradio as gr from transformers import pipeline from transformers import AutoTokenizer, ViTFeatureExtractor, VisionEncoderDecoderModel # Load text generation model text_generation_model = pipeline("text-generation", model="microsoft/Phi-3-mini-4k-instruct", trust_remote_code=True) # Load image captioning model encoder_checkpoint = "nlpconnect/vit-gpt2-image-captioning" decoder_checkpoint = "nlpconnect/vit-gpt2-image-captioning" model_checkpoint = "nlpconnect/vit-gpt2-image-captioning" feature_extractor = ViTFeatureExtractor.from_pretrained(encoder_checkpoint) tokenizer = AutoTokenizer.from_pretrained(decoder_checkpoint) model = VisionEncoderDecoderModel.from_pretrained(model_checkpoint) def generate_story(image, theme, genre): try: # Preprocess the image image = image.convert('RGB') image_features = feature_extractor(images=image, return_tensors="pt") # Generate image caption caption_ids = model.generate(image_features.pixel_values, max_length=50, num_beams=3, temperature=1.0) # Decode the caption caption_text = tokenizer.batch_decode(caption_ids, skip_special_tokens=True)[0] # Generate story based on the caption story_prompt = f"Write an interesting {theme} story in the {genre} genre. The story should be about {caption_text}." story = text_generation_model(story_prompt, max_length=150)[0]["generated_text"] return story except Exception as e: return f"An error occurred during inference: {str(e)}" # Gradio interface input_image = gr.Image(label="Select Image",type="pil") input_theme = gr.Dropdown(["Love and Loss", "Identity and Self-Discovery", "Power and Corruption", "Redemption and Forgiveness", "Survival and Resilience", "Nature and the Environment", "Justice and Injustice", "Friendship and Loyalty", "Hope and Despair"], label="Input Theme") input_genre = gr.Dropdown(["Fantasy", "Science Fiction", "Poetry", "Mystery/Thriller", "Romance", "Historical Fiction", "Horror", "Adventure", "Drama", "Comedy"], label="Input Genre") output_text = gr.Textbox(label="Generated Story",lines=8) gr.Interface( fn=generate_story, inputs=[input_image, input_theme, input_genre], outputs=output_text, title="Image to Story Generator", description="Generate a story from an image taking theme and genre as input.", ).launch()