File size: 5,253 Bytes
b7bcd21
 
 
dc486e8
b7bcd21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13fe7bb
b7bcd21
 
 
 
dc486e8
 
 
b7bcd21
 
 
 
 
 
 
 
 
 
 
 
1c5033d
b7bcd21
 
 
 
 
 
 
 
 
13fe7bb
 
b7bcd21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5033d
 
 
 
dffb3b3
b7bcd21
dffb3b3
b7bcd21
 
dffb3b3
 
b7bcd21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import streamlit as st
import os
import torch
from transformers import pipeline
from diffusers import StableDiffusionPipeline
from PIL import Image
import io

# --- Helper Functions ---
@st.cache_resource
def load_models():
    """Loads and caches the models for both text and image generation."""
    try:
        # Load Text Generation Model (e.g., a smaller model like distilgpt2 for demo)
        st.write("Loading content generation model...")
        text_generator_pipeline = pipeline("text-generation", model="distilgpt2", device=0 if torch.cuda.is_available() else -1)

        # Load Image Generation Model (Stable Diffusion)
        st.write("Loading image generation model...")
        model_id = "segmind/tiny-sd" # Using a very lightweight model
        pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32)
        if torch.cuda.is_available():
            pipe = pipe.to("cuda")
        
        # Add memory optimizations
        pipe.enable_attention_slicing()
        
        return text_generator_pipeline, pipe
    except Exception as e:
        st.error(f"Failed to load models. This might be due to insufficient resources on the hosting environment. Error: {e}")
        st.stop()

# Set up the Streamlit page configuration
st.set_page_config(
    page_title="Multimodal AI Assistant",
    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; }
    
    /* General Streamlit button style */
    .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 AI Oracle 🏛️")
st.markdown("### A Multimodal Content & Image Generation Assistant")
st.markdown("""
This application uses open-source AI models from Hugging Face for all its features.
""")

# Load models and pipelines
text_gen_pipeline, image_gen_pipe = load_models()

# ---- Sidebar for Navigation ----
with st.sidebar:
    st.header("App Features 🔮")
    feature_selection = st.radio(
        "Choose a feature:",
        ["Image Generator", "Content Creator"]
    )

# ---- Main Content Area ----
if feature_selection == "Image Generator":
    st.header("AI Image Generation 🖼️")
    st.markdown("Enter your prompt and let the AI create an image from scratch.")
    
    text_prompt = st.text_input("Enter your image prompt:")

    if st.button("Generate Image"):
        if text_prompt:
            with st.spinner("Generating image with Stable Diffusion..."):
                try:
                    image = image_gen_pipe(text_prompt).images[0]
                    st.image(image, caption=f"Generated from: {text_prompt}")
                except Exception as e:
                    st.error(f"Error generating image. The model might have run out of memory. Error: {e}")
        else:
            st.warning("Please provide a prompt to generate an image.")

elif feature_selection == "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)