File size: 7,569 Bytes
3fcc68f 2656479 3fcc68f | 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 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | # Install required packages
#!pip install transformers gradio torch sentencepiece
import gradio as gr
from transformers import pipeline
print("π Setting up AI pipelines...")
# Initialize all pipelines with specific models for better performance
pipelines = {
"sentiment": pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english"),
"text_generation": pipeline("text-generation", model="gpt2", max_length=100),
"qa": pipeline("question-answering", model="distilbert-base-cased-distilled-squad"),
"translation": pipeline("translation_en_to_fr", model="t5-small"),
"summarization": pipeline("summarization", model="facebook/bart-large-cnn"),
"ner": pipeline("ner", aggregation_strategy="simple", model="dbmdz/bert-large-cased-finetuned-conll03-english"),
"zero_shot": pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
}
print("β
All pipelines loaded successfully!")
def ai_playground(task, text, context, labels):
try:
if task == "sentiment":
result = pipelines["sentiment"](text)[0]
emotion = "π" if result['label'] == 'POSITIVE' else 'π'
return f"{emotion} {result['label']} ({result['score']:.2%} confidence)"
elif task == "text_generation":
result = pipelines["text_generation"](text, max_length=100, do_sample=True)[0]['generated_text']
return f"π {result}"
elif task == "qa":
if not context.strip():
return "β Please provide context for question answering"
result = pipelines["qa"](question=text, context=context)
return f"β
Answer: {result['answer']}\nπ― Confidence: {result['score']:.2%}"
elif task == "translation":
result = pipelines["translation"](text)[0]['translation_text']
return f"π«π· {result}"
elif task == "summarization":
if len(text) < 50:
return "β Text is too short for summarization. Please provide longer text."
result = pipelines["summarization"](text, max_length=80, min_length=30, do_sample=False)[0]['summary_text']
return f"π Summary: {result}"
elif task == "ner":
entities = pipelines["ner"](text)
if not entities:
return "π No named entities found"
result = "\n".join([f"β’ {entity['word']} β {entity['entity_group']} ({entity['score']:.2%})" for entity in entities[:10]])
return f"π Found Entities:\n{result}"
elif task == "zero_shot":
if not labels.strip():
return "β Please provide labels for zero-shot classification"
label_list = [label.strip() for label in labels.split(",") if label.strip()]
result = pipelines["zero_shot"](text, label_list, multi_label=False)
formatted_results = "\n".join([f"β’ {label}: {score:.2%}" for label, score in zip(result['labels'][:5], result['scores'][:5])])
return f"π·οΈ Classification:\n{formatted_results}"
else:
return "Please provide required inputs"
except Exception as e:
return f"β Error: {str(e)}"
# Create the interface with better layout
with gr.Blocks(theme=gr.themes.Soft(), title="πͺ AI Playground") as demo:
gr.Markdown("# πͺ AI Playground - Try Everything!")
gr.Markdown("Perfect for beginners! Choose a task and see AI in action. Built for Google Colab! π")
with gr.Row():
with gr.Column(scale=1):
task_dropdown = gr.Dropdown(
choices=["sentiment", "text_generation", "qa", "translation", "summarization", "ner", "zero_shot"],
label="π― Choose AI Task",
value="sentiment",
info="Select what you want to do"
)
input_text = gr.Textbox(
lines=3,
placeholder="Enter your text here...",
label="π Input Text",
value="I love learning about artificial intelligence!"
)
context_text = gr.Textbox(
lines=3,
placeholder="For QA: Enter context here...\nExample: Hugging Face provides AI tools and models. The company was founded in 2016.",
label="π Context (for QA only)",
visible=False
)
labels_text = gr.Textbox(
lines=2,
placeholder="For Zero-shot: Enter comma-separated labels\nExample: positive, negative, neutral",
label="π·οΈ Labels (for Zero-shot only)",
visible=False
)
submit_btn = gr.Button("β¨ Run AI Magic!", variant="primary")
with gr.Column(scale=2):
output_text = gr.Textbox(
lines=8,
label="π AI Output",
interactive=False,
show_copy_button=True
)
# Examples for each task
gr.Markdown("## π‘ Try These Examples:")
examples = [
["sentiment", "I'm so excited to learn about AI!", "", ""],
["text_generation", "Once upon a time in a magical kingdom,", "", ""],
["translation", "Hello, how are you today?", "", ""],
["summarization", "Artificial intelligence is transforming many industries. Machine learning allows computers to learn from data. Deep learning uses neural networks for complex tasks. AI is used in healthcare, finance, and transportation.", "", ""],
["ner", "Apple was founded by Steve Jobs in Cupertino, California in 1976.", "", ""],
["zero_shot", "The new smartphone has amazing battery life and camera quality.", "", "technology, review, complaint, inquiry"],
["qa", "What does Hugging Face provide?", "Hugging Face is a company that provides AI tools and models for natural language processing. Their library makes it easy to use state-of-the-art models.", ""]
]
gr.Examples(
examples=examples,
inputs=[task_dropdown, input_text, context_text, labels_text],
outputs=output_text,
fn=ai_playground,
cache_examples=False,
label="Click any example below to try it!"
)
# Show/hide context and labels based on task selection
def toggle_inputs(task):
context_visible = (task == "qa")
labels_visible = (task == "zero_shot")
return [
gr.Textbox(visible=context_visible),
gr.Textbox(visible=labels_visible)
]
task_dropdown.change(
fn=toggle_inputs,
inputs=task_dropdown,
outputs=[context_text, labels_text]
)
# Connect the submit button
submit_btn.click(
fn=ai_playground,
inputs=[task_dropdown, input_text, context_text, labels_text],
outputs=output_text
)
gr.Markdown("---")
gr.Markdown("### π Learning Tips:")
gr.Markdown("""
- **Sentiment Analysis**: Detects positive/negative emotions in text
- **Text Generation**: Creates new text based on your prompt
- **Translation**: Translates English to French
- **Summarization**: Shortens long text while keeping key points
- **Named Entity Recognition**: Finds people, places, organizations in text
- **Zero-Shot Classification**: Classifies text into custom categories
- **Question Answering**: Answers questions based on provided context
""")
print("π AI Playground is ready! Launching interface...")
demo.launch(share=True, debug=True) |