Sentiment analysis, Python UI development, and Gradio interfaces combine to create powerful text analysis applications. This guide shows you how to build a sentiment analysis tool using Google Colab’s free GPU resources with Gradio’s interface components.
source code : [SMKDEV] Simple Gradio Demo – Sentiment Analysis
Setting Up Google Colab Environment
First, create a new Google Colab notebook by visiting Google Colab. Then install the required packages:
!pip install gradio transformers --quiet
Importing Libraries
In a new code cell, import the necessary libraries:
import gradio as gr
from transformers import pipeline
Configuring HuggingFace Authentication
To use HuggingFace models in Colab, follow these steps:
- Create a HuggingFace account at HuggingFace.co
- Generate an access token:
- Go to Settings > Access Tokens
- Create a new token with ‘read’ access
- Add the token to Colab:
# Option 1: Using Colab Secrets (Recommended)
# Go to Colab menu: Tools > Settings > Secrets
# Add new secret with name "HF_TOKEN"
# Option 2: Direct assignment (for testing only)
# hf_token = "your_hf_token_here"
Creating the Sentiment Analysis Interface
Initialize the Model
# Load the sentiment analysis model
model = pipeline("sentiment-analysis")
# If using HuggingFace token:
# model = pipeline("sentiment-analysis", use_auth_token=hf_token)
Define Analysis Function
def analyze_sentiment(text):
results = model(text)
return f"Label: {results[0]['label']}, Score: {results[0]['score']:.4f}"
Building the Colab-Compatible Interface
# Create enhanced interface with Gradio Blocks
with gr.Blocks() as demo:
# Header
gr.Markdown("# Sentiment Analysis in Google Colab")
gr.Markdown("## Analyze the emotional tone of your text")
# Interface layout
with gr.Row():
with gr.Column():
input_text = gr.Textbox(
lines=2,
placeholder="Enter your text here...",
label="Input Text"
)
analyze_button = gr.Button("Analyze Sentiment")
with gr.Column():
output_text = gr.Textbox(
label="Analysis Result",
interactive=False
)
# Connect function to button
analyze_button.click(
fn=analyze_sentiment,
inputs=input_text,
outputs=output_text
)
# Launch with sharing enabled for Colab
demo.launch(share=True)
Running in Google Colab
Important Colab-Specific Tips
- Runtime Management:
- Select Runtime > Change runtime type
- Choose ‘GPU’ for faster processing
- Click ‘Connect’ to ensure active runtime
- Sharing Your Interface:
# The share=True parameter creates a public URL
# Valid for 72 hours
demo.launch(share=True)
- Saving Your Work:
- File > Save a copy in Drive
- Creates a permanent copy in your Google Drive
Advanced Colab Features
Adding Requirements File
Create a requirements.txt in Colab:
%%writefile requirements.txt
transformers
torch
gradio
Creating a Deployable App File
%%writefile app.py
import gradio as gr
from transformers import pipeline
model = pipeline("sentiment-analysis")
def analyze_sentiment(text):
results = model(text)
return f"Label: {results[0]['label']}, Score: {results[0]['score']:.4f}"
# Create interface
demo = gr.Interface(
fn=analyze_sentiment,
inputs=gr.Textbox(lines=2, placeholder="Enter text..."),
outputs=gr.Textbox(),
title="Sentiment Analysis",
description="Analyze the emotional tone of text"
)
if __name__ == "__main__":
demo.launch()
Best Practices for Colab Usage
- Session Management:
- Colab sessions timeout after 90 minutes of inactivity
- Save your work frequently
- Download important files locally
- Resource Optimization:
# Clear memory when needed
import gc
gc.collect()
- Error Handling:
def analyze_sentiment(text):
try:
results = model(text)
return f"Label: {results[0]['label']}, Score: {results[0]['score']:.4f}"
except Exception as e:
return f"Error: Please check your input and try again. ({str(e)})"
Additional Resources
Conclusion
Google Colab provides an excellent platform for developing and testing Gradio interfaces. Its free GPU resources and collaborative features make it perfect for experimenting with sentiment analysis applications. Remember to save your work and manage your authentication tokens securely when working in Colab.
Discover more from teguhteja.id
Subscribe to get the latest posts sent to your email.