Download app.py from Hassan501/MultimodalApplication_GENAI: direct link, hf CLI and curl.
- Browser
- Download file 5.57 kB
-
https://huggingface.co/spaces/Hassan501/MultimodalApplication_GENAI/resolve/main/app.py
- Command line
-
hf download hf://spaces/Hassan501/MultimodalApplication_GENAI/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Hassan501/MultimodalApplication_GENAI/resolve/main/app.py
5.57 kB
| import streamlit as st | |
| import os | |
| import torch | |
| from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM | |
| from PIL import Image | |
| import io | |
| # --- Helper Functions --- | |
| def load_models(): | |
| """Loads and caches the models for both content generation and image captioning.""" | |
| try: | |
| # Load Text Generation Model (e.g., distilgpt2 for demo/efficiency) | |
| st.write("Loading content generation model (distilgpt2)...") | |
| text_generator_pipeline = pipeline("text-generation", model="distilgpt2", device=0 if torch.cuda.is_available() else -1) | |
| # Load Image Captioning Model (e.g., Salesforce/blip-image-captioning-base) | |
| st.write("Loading image captioning model (BLIP)...") | |
| # Ensure you have a GPU for this, or it will be very slow on CPU | |
| captioner_pipeline = pipeline( | |
| "image-to-text", | |
| model="Salesforce/blip-image-captioning-base", | |
| device=0 if torch.cuda.is_available() else -1 | |
| ) | |
| return text_generator_pipeline, captioner_pipeline | |
| except Exception as e: | |
| st.error(f"Failed to load models. This might be due to insufficient resources on the hosting environment or a dependency issue. Error: {e}") | |
| st.stop() | |
| # Set up the Streamlit page configuration | |
| st.set_page_config( | |
| page_title="Multimodal AI Assistant (Caption & Content)", | |
| layout="wide", | |
| initial_sidebar_state="expanded" | |
| ) | |
| # Custom CSS for a classic and elegant look | |
| st.markdown( | |
| """ | |
| <style> | |
| .reportview-container { background: #f0f2f6; } | |
| .main .block-container { max-width: 1200px; padding-top: 2rem; } | |
| .st-emotion-cache-1c5c56c { background-color: #f0f2f6; } | |
| .sidebar .sidebar-content { background-color: #ffffff; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2); } | |
| h1 { color: #333333; font-family: serif; text-align: center; } | |
| h2 { color: #555555; font-family: serif; } | |
| .stButton>button { | |
| background-color: #4CAF50; color: white; border: none; padding: 10px 24px; | |
| text-align: center; text-decoration: none; display: inline-block; | |
| font-size: 16px; margin: 4px 2px; cursor: pointer; border-radius: 12px; | |
| transition: all 0.3s ease-in-out; | |
| } | |
| .stButton>button:hover { background-color: #45a049; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2); } | |
| .stImage { border-radius: 12px; } | |
| </style> | |
| """, | |
| unsafe_allow_html=True | |
| ) | |
| st.title("🏛️ The Multimodal AI Oracle 🏛️") | |
| st.markdown("### Image Captioning & Creative Content Generation") | |
| st.markdown(""" | |
| This application combines image understanding with creative text generation, powered by open-source AI models from Hugging Face. | |
| """) | |
| # Load models and pipelines | |
| text_gen_pipeline, captioner_pipeline = load_models() | |
| # ---- Sidebar for Navigation ---- | |
| with st.sidebar: | |
| st.header("App Features 🔮") | |
| feature_selection = st.radio( | |
| "Choose a feature:", | |
| ["Image Caption Generator", "AI-Powered Content Creator"] | |
| ) | |
| # ---- Main Content Area ---- | |
| if feature_selection == "Image Caption Generator": | |
| st.header("Image Captioning 📸") | |
| st.markdown("Upload an image and let the AI describe it for you.") | |
| uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"]) | |
| if uploaded_file is not None: | |
| image = Image.open(uploaded_file) | |
| st.image(image, caption="Uploaded Image", use_column_width=True) | |
| if st.button("Generate Caption"): | |
| with st.spinner("Generating caption..."): | |
| try: | |
| # BLIP models typically return a list of dicts, take the 'generated_text' | |
| caption_results = captioner_pipeline(image) | |
| generated_caption = caption_results[0]['generated_text'] | |
| st.success("Caption Generated!") | |
| st.info(f"**Caption:** {generated_caption}") | |
| except Exception as e: | |
| st.error(f"Error generating caption: {e}") | |
| else: | |
| st.info("Please upload an image to get a caption.") | |
| elif feature_selection == "AI-Powered Content Creator": | |
| st.header("AI-Powered Content Creator ✍️") | |
| st.markdown("Tell the AI what you want to create and get instant results!") | |
| content_type = st.selectbox( | |
| "Choose content type:", | |
| ["Article", "Poem", "Short Story"] | |
| ) | |
| topic = st.text_input("Enter the topic or a starting sentence:") | |
| length = st.slider("Select desired length:", 50, 500, 150, step=50) | |
| if st.button("Generate Content"): | |
| if topic: | |
| with st.spinner("Generating content..."): | |
| try: | |
| full_prompt = f"Write a {content_type.lower()} about '{topic}'. " | |
| response = text_gen_pipeline( | |
| full_prompt, | |
| max_length=length, | |
| num_return_sequences=1 | |
| ) | |
| generated_text = response[0]['generated_text'] | |
| st.success("Content Generated!") | |
| st.markdown("---") | |
| st.markdown(generated_text) | |
| st.markdown("---") | |
| except Exception as e: | |
| st.error(f"Error generating content: {e}") | |
| else: | |
| st.warning("Please enter a topic or starting sentence.") | |
| st.markdown(""" | |
| --- | |
| <p style="text-align: center; color: gray;"> | |
| Powered by the Hugging Face `transformers` library ✨ | |
| </p> | |
| """, unsafe_allow_html=True) |