txt2imghost / app.py
ghostai1's picture
Update app.py
540a829 verified
import gradio as gr
from transformers import pipeline
import numpy as np
from PIL import Image
import io
import base64
# Initialize sentiment analysis pipeline (lightweight for CPU)
sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
# Mock text-to-image function (CPU-friendly)
def generate_mock_image(text_prompt, width=200, height=200):
img_array = np.zeros((height, width, 3), dtype=np.uint8)
for i in range(height):
for j in range(width):
img_array[i, j] = [(i % 255), (j % 255), ((i + j) % 255)] # RGB gradient
img = Image.fromarray(img_array)
buffered = io.BytesIO()
img.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
return f"data:image/png;base64,{img_str}"
# Sentiment analysis function
def analyze_sentiment(text):
if not text.strip():
return "Please enter some text."
result = sentiment_analyzer(text)[0]
label = result['label']
score = result['score']
return f"Sentiment: {label} (Confidence: {score:.2%})"
# Chatbot feedback function
def chatbot_response(user_feedback, chat_history):
if not user_feedback.strip():
return chat_history, "Please provide feedback."
chat_history.append((
f"**You**: {user_feedback}",
f"**Bot**: Thanks for your feedback! I understood: '{user_feedback}'."
))
return chat_history, ""
# Custom CSS for dark grey, minimalist UI
custom_css = """
body, .gradio-container {
background: #2d2d2d !important;
color: #d4d4d4 !important;
font-family: 'Inter', -apple-system, sans-serif;
margin: 0;
padding: 20px;
}
.tab-nav button {
background: #3a3a3a !important;
color: #a3a3a3 !important;
border: none !important;
padding: 12px 20px !important;
border-radius: 8px 8px 0 0 !important;
transition: background 0.3s, color 0.3s;
}
.tab-nav button:hover, .tab-nav button[aria-selected="true"] {
background: #4a4a4a !important;
color: #e0e0e0 !important;
}
.block, .gr-panel {
background: #353535 !important;
border-radius: 10px !important;
padding: 20px !important;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.25);
margin-bottom: 20px;
}
input, textarea, .gr-textbox {
background: #2a2a2a !important;
color: #d4d4d4 !important;
border: 1px solid #4a4a4a !important;
border-radius: 8px !important;
padding: 12px !important;
transition: border-color 0.2s;
}
input:focus, textarea:focus {
border-color: #6b6b6b !important;
outline: none;
}
button {
background: #4a4a4a !important;
color: #e0e0e0 !important;
border: none !important;
border-radius: 8px !important;
padding: 12px 24px !important;
font-weight: 600;
transition: background 0.2s, transform 0.2s;
}
button:hover {
background: #5a5a5a !important;
transform: scale(1.03);
}
.gr-image img {
border-radius: 8px !important;
border: 2px solid #4a4a4a !important;
max-width: 100%;
}
.gr-chatbot .message {
border-radius: 8px !important;
padding: 12px !important;
margin: 8px 0 !important;
}
.gr-chatbot .message:nth-child(odd) {
background: #3a3a3a !important; /* User messages */
}
.gr-chatbot .message:nth-child(even) {
background: #2a2a2a !important; /* Bot messages */
}
h1, h2, h3 {
color: #b3b3b3 !important;
font-weight: 600;
}
@media (max-width: 768px) {
.gradio-container {
padding: 10px;
}
.block {
padding: 15px !important;
}
button {
padding: 10px 20px !important;
}
.tab-nav button {
padding: 10px 15px !important;
font-size: 14px;
}
}
"""
# Main Gradio app with Tabs
with gr.Blocks(css=custom_css) as demo:
gr.Markdown(
"""
# ๐Ÿ› ๏ธ Interactive AI Dashboard
Explore **Sentiment Analysis**, **Text-to-Image Generation**, and **Feedback Chatbot** in a sleek grey interface.
Built for Hugging Face Spaces (free tier, CPU-only).
"""
)
with gr.Tabs():
# Sentiment Analysis Tab
with gr.Tab("Sentiment Analysis"):
with gr.Row():
with gr.Column(scale=3):
gr.Markdown("### ๐Ÿ“ Analyze Text Sentiment")
sentiment_input = gr.Textbox(
label="Your Text",
placeholder="Enter text like 'This app is awesome!'",
lines=4,
show_label=False
)
sentiment_button = gr.Button("Analyze", variant="primary")
sentiment_output = gr.Textbox(
label="Result",
interactive=False,
placeholder="Sentiment result will appear here..."
)
with gr.Column(scale=2):
gr.Markdown("### Example Prompts")
gr.Examples(
examples=[
"Iโ€™m thrilled about this project!",
"Today feels a bit gloomy.",
"Programming is tough but rewarding!"
],
inputs=sentiment_input
)
sentiment_button.click(
fn=analyze_sentiment,
inputs=sentiment_input,
outputs=sentiment_output,
show_progress=True
)
# Text-to-Image Tab
with gr.Tab("Text-to-Image"):
with gr.Row():
with gr.Column(scale=3):
gr.Markdown("### ๐Ÿ–ผ๏ธ Generate Mock Images")
image_prompt = gr.Textbox(
label="Image Prompt",
placeholder="Describe an image, e.g., 'Abstract colorful pattern'",
lines=3,
show_label=False
)
image_button = gr.Button("Generate", variant="primary")
image_output = gr.Image(
label="Generated Image",
type="pil",
interactive=False
)
with gr.Column(scale=2):
gr.Markdown("### Info")
gr.Markdown(
"This mock generator creates gradient images to stay lightweight for the free tier."
)
image_button.click(
fn=generate_mock_image,
inputs=image_prompt,
outputs=image_output,
show_progress=True
)
# Chatbot Tab
with gr.Tab("Feedback Chatbot"):
with gr.Row():
with gr.Column():
gr.Markdown("### ๐Ÿ’ฌ Share Your Thoughts")
chatbot = gr.Chatbot(
label="Conversation",
bubble_full_width=False,
height=400
)
feedback_input = gr.Textbox(
label="Your Message",
placeholder="Type your feedback here...",
lines=2,
show_label=False
)
feedback_button = gr.Button("Send", variant="primary")
feedback_output = gr.Textbox(
label="Status",
interactive=False,
placeholder="Bot response status..."
)
feedback_button.click(
fn=chatbot_response,
inputs=[feedback_input, chatbot],
outputs=[chatbot, feedback_output],
show_progress=True
)
# Launch the app
if __name__ == "__main__":
demo.launch()