mcp-sentiment / usage /sentiment_gradio_client_usage.py
phil71x
feat: Introduce new sentiment analysis scripts and rename other scripts . Enhance documentation
23d394c
#!/usr/bin/env python3
"""
Gradio Sentiment Analysis (Backup Solution).
This script provides sentiment analysis using the Gradio client library to connect
directly to the Hugging Face Space API, bypassing the MCP protocol entirely.
Performance: ~1.3 seconds per request
Protocol: Direct Gradio API access
To run this script:
pdm run python usage/sentiment_gradio.py
Dependencies:
- gradio_client (already installed)
This is a reliable backup solution when MCP protocol has issues.
"""
import time
from gradio_client import Client
def analyze_sentiment(text):
"""Analyze sentiment of a single text using Gradio client."""
try:
client = Client("https://freemansel-mcp-sentiment.hf.space")
result = client.predict(text, api_name="/predict")
return result
except Exception as e:
return {"error": str(e)}
def main():
"""Main function to test sentiment analysis with Gradio client."""
print("πŸ§ͺ Gradio Sentiment Analysis (Backup Solution)")
print("=" * 50)
print("Using Gradio client to connect directly to the Hugging Face Space.")
print("This bypasses MCP protocol issues.")
print()
# Test texts
test_texts = [
"I love this product! It's amazing!",
"This is terrible. I hate it.",
"It's okay, nothing special.",
"The weather is beautiful today!",
"I'm feeling quite neutral about this.",
"This is the worst experience ever!",
"Absolutely fantastic and wonderful!",
]
print("⏳ Connecting to Hugging Face Space...")
try:
client = Client("https://freemansel-mcp-sentiment.hf.space")
print("βœ… Connected successfully!")
print()
# Analyze each text
for i, text in enumerate(test_texts, 1):
print(f"Test {i}: '{text}'")
start_time = time.time()
try:
result = client.predict(text, api_name="/predict")
elapsed = time.time() - start_time
print(f" πŸ“Š Polarity: {result.get('polarity', 'N/A')}")
print(f" πŸ“Š Subjectivity: {result.get('subjectivity', 'N/A')}")
print(f" πŸ“Š Assessment: {result.get('assessment', 'N/A')}")
print(f" ⏱️ Time: {elapsed:.2f}s")
except Exception as e:
print(f" ❌ Error: {e}")
print()
print("πŸŽ‰ Gradio sentiment analysis completed!")
print("\nπŸ“‹ Summary:")
print("βœ… Hugging Face Space is working")
print("βœ… Gradio client connection works")
print("βœ… Sentiment analysis API is functional")
print("ℹ️ For faster results, try: pdm run python usage/sentiment_mcp.py")
except Exception as e:
print(f"❌ Failed to connect: {e}")
print("\nTroubleshooting:")
print("1. Check internet connection")
print("2. Verify the Hugging Face Space is running")
print("3. Make sure gradio_client is installed: pdm add gradio_client")
print("4. Try the MCP solution: pdm run python usage/sentiment_mcp.py")
if __name__ == "__main__":
main()