Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| from data_clean import clean_text | |
| from data_process import query_hf_sentiment, extract_themes, create_openai_client | |
| import os | |
| from dotenv import load_dotenv | |
| # Load environment variables | |
| load_dotenv() | |
| API_KEY = os.getenv("API_KEY") | |
| brear_token=os.getenv("BEARER_TOKEN") | |
| HF_MODEL_URL = "https://api-inference.huggingface.co/models/tabularisai/multilingual-sentiment-analysis" | |
| def analyze_post_gradio(post: str): | |
| """Gradio version of the analyze_post function.""" | |
| try: | |
| if not post or not post.strip(): | |
| return "β οΈ Please enter a valid post before analyzing." | |
| # Clean the text | |
| cleaned_post = clean_text(post) | |
| # Get sentiment analysis | |
| sentiment_result = query_hf_sentiment(cleaned_post, brear_token, HF_MODEL_URL) | |
| # Handle possible formats of HF output | |
| if isinstance(sentiment_result, dict) and "raw_output" in sentiment_result: | |
| sentiment = sentiment_result["raw_output"][0] | |
| elif isinstance(sentiment_result, list) and len(sentiment_result) > 0: | |
| sentiment = sentiment_result[0] | |
| else: | |
| sentiment = {"label": "Unknown", "score": 0.0} | |
| # Extract themes | |
| openai_client = create_openai_client(API_KEY) | |
| themes = extract_themes(cleaned_post, openai_client) | |
| # Prepare data | |
| output = f""" | |
| ### π§Ύ **Original Post** | |
| {post} | |
| ### π§Ή **Cleaned Post** | |
| {cleaned_post} | |
| ### π¬ **Sentiment Analysis** | |
| - **Label:** {sentiment.get('label', 'Unknown')} | |
| - **Score:** {sentiment.get('score', 0.0):.4f} | |
| ### π·οΈ **Extracted Themes** | |
| {themes} | |
| β **Status:** Post analyzed successfully. | |
| """ | |
| return output | |
| except Exception as e: | |
| return f"β **Error analyzing post:** {str(e)}" | |
| # --- Gradio Interface --- | |
| with gr.Blocks(title="Post Analyzer", theme=gr.themes.Soft()) as demo: | |
| gr.Markdown("# π Post Analysis Tool") | |
| gr.Markdown("Enter a post to analyze its sentiment and extract key themes using AI models.") | |
| with gr.Row(): | |
| with gr.Column(): | |
| post_input = gr.Textbox( | |
| label="Enter your post", | |
| placeholder="Type your post here...", | |
| lines=4, | |
| max_lines=10, | |
| ) | |
| analyze_btn = gr.Button("π Analyze Post", variant="primary") | |
| with gr.Column(): | |
| output = gr.Markdown("Results will appear here after analysis...") | |
| analyze_btn.click( | |
| fn=analyze_post_gradio, | |
| inputs=post_input, | |
| outputs=output, | |
| ) | |
| gr.Examples( | |
| examples=[ | |
| "I absolutely love this product! It's amazing and works perfectly.", | |
| "I'm really disappointed with the service. It was slow and unhelpful.", | |
| "The weather today is nice, but I'm concerned about climate change.", | |
| ], | |
| inputs=post_input, | |
| ) | |
| # --- Launch for Hugging Face Space --- | |
| if __name__ == "__main__": | |
| demo.launch() | |