Rahaf2001 commited on
Commit
3fcc68f
Β·
verified Β·
1 Parent(s): d262aa2

Create App.py

Browse files
Files changed (1) hide show
  1. App.py +172 -0
App.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Install required packages
2
+ !pip install transformers gradio torch sentencepiece
3
+
4
+ import gradio as gr
5
+ from transformers import pipeline
6
+
7
+ print("πŸš€ Setting up AI pipelines...")
8
+
9
+ # Initialize all pipelines with specific models for better performance
10
+ pipelines = {
11
+ "sentiment": pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english"),
12
+ "text_generation": pipeline("text-generation", model="gpt2", max_length=100),
13
+ "qa": pipeline("question-answering", model="distilbert-base-cased-distilled-squad"),
14
+ "translation": pipeline("translation_en_to_fr", model="t5-small"),
15
+ "summarization": pipeline("summarization", model="facebook/bart-large-cnn"),
16
+ "ner": pipeline("ner", aggregation_strategy="simple", model="dbmdz/bert-large-cased-finetuned-conll03-english"),
17
+ "zero_shot": pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
18
+ }
19
+
20
+ print("βœ… All pipelines loaded successfully!")
21
+
22
+ def ai_playground(task, text, context, labels):
23
+ try:
24
+ if task == "sentiment":
25
+ result = pipelines["sentiment"](text)[0]
26
+ emotion = "😊" if result['label'] == 'POSITIVE' else '😞'
27
+ return f"{emotion} {result['label']} ({result['score']:.2%} confidence)"
28
+
29
+ elif task == "text_generation":
30
+ result = pipelines["text_generation"](text, max_length=100, do_sample=True)[0]['generated_text']
31
+ return f"πŸ“ {result}"
32
+
33
+ elif task == "qa":
34
+ if not context.strip():
35
+ return "❌ Please provide context for question answering"
36
+ result = pipelines["qa"](question=text, context=context)
37
+ return f"βœ… Answer: {result['answer']}\n🎯 Confidence: {result['score']:.2%}"
38
+
39
+ elif task == "translation":
40
+ result = pipelines["translation"](text)[0]['translation_text']
41
+ return f"πŸ‡«πŸ‡· {result}"
42
+
43
+ elif task == "summarization":
44
+ if len(text) < 50:
45
+ return "❌ Text is too short for summarization. Please provide longer text."
46
+ result = pipelines["summarization"](text, max_length=80, min_length=30, do_sample=False)[0]['summary_text']
47
+ return f"πŸ“Œ Summary: {result}"
48
+
49
+ elif task == "ner":
50
+ entities = pipelines["ner"](text)
51
+ if not entities:
52
+ return "πŸ” No named entities found"
53
+ result = "\n".join([f"β€’ {entity['word']} β†’ {entity['entity_group']} ({entity['score']:.2%})" for entity in entities[:10]])
54
+ return f"πŸ” Found Entities:\n{result}"
55
+
56
+ elif task == "zero_shot":
57
+ if not labels.strip():
58
+ return "❌ Please provide labels for zero-shot classification"
59
+ label_list = [label.strip() for label in labels.split(",") if label.strip()]
60
+ result = pipelines["zero_shot"](text, label_list, multi_label=False)
61
+ formatted_results = "\n".join([f"β€’ {label}: {score:.2%}" for label, score in zip(result['labels'][:5], result['scores'][:5])])
62
+ return f"🏷️ Classification:\n{formatted_results}"
63
+
64
+ else:
65
+ return "Please provide required inputs"
66
+
67
+ except Exception as e:
68
+ return f"❌ Error: {str(e)}"
69
+
70
+ # Create the interface with better layout
71
+ with gr.Blocks(theme=gr.themes.Soft(), title="πŸŽͺ AI Playground") as demo:
72
+ gr.Markdown("# πŸŽͺ AI Playground - Try Everything!")
73
+ gr.Markdown("Perfect for beginners! Choose a task and see AI in action. Built for Google Colab! πŸš€")
74
+
75
+ with gr.Row():
76
+ with gr.Column(scale=1):
77
+ task_dropdown = gr.Dropdown(
78
+ choices=["sentiment", "text_generation", "qa", "translation", "summarization", "ner", "zero_shot"],
79
+ label="🎯 Choose AI Task",
80
+ value="sentiment",
81
+ info="Select what you want to do"
82
+ )
83
+
84
+ input_text = gr.Textbox(
85
+ lines=3,
86
+ placeholder="Enter your text here...",
87
+ label="πŸ“ Input Text",
88
+ value="I love learning about artificial intelligence!"
89
+ )
90
+
91
+ context_text = gr.Textbox(
92
+ lines=3,
93
+ placeholder="For QA: Enter context here...\nExample: Hugging Face provides AI tools and models. The company was founded in 2016.",
94
+ label="πŸ“š Context (for QA only)",
95
+ visible=False
96
+ )
97
+
98
+ labels_text = gr.Textbox(
99
+ lines=2,
100
+ placeholder="For Zero-shot: Enter comma-separated labels\nExample: positive, negative, neutral",
101
+ label="🏷️ Labels (for Zero-shot only)",
102
+ visible=False
103
+ )
104
+
105
+ submit_btn = gr.Button("✨ Run AI Magic!", variant="primary")
106
+
107
+ with gr.Column(scale=2):
108
+ output_text = gr.Textbox(
109
+ lines=8,
110
+ label="πŸŽ‰ AI Output",
111
+ interactive=False,
112
+ show_copy_button=True
113
+ )
114
+
115
+ # Examples for each task
116
+ gr.Markdown("## πŸ’‘ Try These Examples:")
117
+
118
+ examples = [
119
+ ["sentiment", "I'm so excited to learn about AI!", "", ""],
120
+ ["text_generation", "Once upon a time in a magical kingdom,", "", ""],
121
+ ["translation", "Hello, how are you today?", "", ""],
122
+ ["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.", "", ""],
123
+ ["ner", "Apple was founded by Steve Jobs in Cupertino, California in 1976.", "", ""],
124
+ ["zero_shot", "The new smartphone has amazing battery life and camera quality.", "", "technology, review, complaint, inquiry"],
125
+ ["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.", ""]
126
+ ]
127
+
128
+ gr.Examples(
129
+ examples=examples,
130
+ inputs=[task_dropdown, input_text, context_text, labels_text],
131
+ outputs=output_text,
132
+ fn=ai_playground,
133
+ cache_examples=False,
134
+ label="Click any example below to try it!"
135
+ )
136
+
137
+ # Show/hide context and labels based on task selection
138
+ def toggle_inputs(task):
139
+ context_visible = (task == "qa")
140
+ labels_visible = (task == "zero_shot")
141
+ return [
142
+ gr.Textbox(visible=context_visible),
143
+ gr.Textbox(visible=labels_visible)
144
+ ]
145
+
146
+ task_dropdown.change(
147
+ fn=toggle_inputs,
148
+ inputs=task_dropdown,
149
+ outputs=[context_text, labels_text]
150
+ )
151
+
152
+ # Connect the submit button
153
+ submit_btn.click(
154
+ fn=ai_playground,
155
+ inputs=[task_dropdown, input_text, context_text, labels_text],
156
+ outputs=output_text
157
+ )
158
+
159
+ gr.Markdown("---")
160
+ gr.Markdown("### πŸŽ“ Learning Tips:")
161
+ gr.Markdown("""
162
+ - **Sentiment Analysis**: Detects positive/negative emotions in text
163
+ - **Text Generation**: Creates new text based on your prompt
164
+ - **Translation**: Translates English to French
165
+ - **Summarization**: Shortens long text while keeping key points
166
+ - **Named Entity Recognition**: Finds people, places, organizations in text
167
+ - **Zero-Shot Classification**: Classifies text into custom categories
168
+ - **Question Answering**: Answers questions based on provided context
169
+ """)
170
+
171
+ print("πŸŽ‰ AI Playground is ready! Launching interface...")
172
+ demo.launch(share=True, debug=True)