import gradio as gr from transformers import pipeline # --- 1. Load your model from the Hugging Face Hub --- # Replace 'your-username/your-sentiment-model' with the actual name of your model. # The pipeline will automatically download and cache the model. try: sentiment_pipeline = pipeline( "sentiment-analysis", model="Relacosm/mca-sentiment-analyzer-v2" # ⬅️ CHANGE THIS ) print("Model loaded successfully!") except Exception as e: print(f"Error loading model: {e}") sentiment_pipeline = None # Handle case where model fails to load # --- 2. Define the prediction function --- # This function will take a string of text as input and return the model's prediction. def predict_sentiment(text): if sentiment_pipeline is None: return {"error": "Model is not available. Please check the logs."} # The pipeline returns a list of dictionaries, e.g., [{'label': 'Positive', 'score': 0.99}] results = sentiment_pipeline(text) # We'll return the dictionary directly for Gradio's Label component # It will automatically display the label and its confidence score. return {result['label']: result['score'] for result in results} # --- 3. Create the Gradio interface --- # This creates the web UI with input and output components. iface = gr.Interface( fn=predict_sentiment, inputs=gr.Textbox(lines=5, placeholder="Enter your text here..."), outputs=gr.Label(num_top_classes=3), # The Label component is great for classification title="Sentiment Analysis Demo", description="Enter some text to see the sentiment prediction from a fine-tuned model deployed on Hugging Face Spaces.", examples=[ ["The new city planning initiative is fantastic, very forward-thinking."], ["I am really concerned about the budget allocation for environmental projects."], ["Why was there no public consultation on the new infrastructure project?"] ] ) # --- 4. Launch the app --- # The launch() method creates a web server and makes the UI accessible. if __name__ == "__main__": iface.launch()