import praw from transformers import AutoTokenizer, AutoModelForSequenceClassification import torch import gradio as gr import os # Load your model model_name = "amitkatoch/distilbertonsentiment" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSequenceClassification.from_pretrained(model_name) device = "cuda" if torch.cuda.is_available() else "cpu" model = model.to(device) # Load Reddit API keys from Hugging Face secrets reddit = praw.Reddit( client_id=os.environ["REDDIT_CLIENT_ID"], client_secret=os.environ["REDDIT_CLIENT_SECRET"], user_agent=os.environ["REDDIT_USER_AGENT"] ) def analyze_sentiment(text): inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512).to(device) with torch.no_grad(): outputs = model(**inputs) probs = torch.nn.functional.softmax(outputs.logits, dim=-1) pred = torch.argmax(probs).item() confidence = probs[0][pred].item() return "😊 Positive" if pred == 1 else "😠 Negative", f"{confidence:.2%}" def analyze_reddit(subreddit, num_posts=5): posts = [] for submission in reddit.subreddit(subreddit).new(limit=num_posts): text = submission.title if submission.selftext: text += " " + submission.selftext[:200] sentiment, confidence = analyze_sentiment(text) posts.append({ "Post": submission.title[:50] + "...", "Sentiment": sentiment, "Confidence": confidence, "Link": f"https://reddit.com{submission.permalink}" }) return posts # Gradio UI with gr.Blocks() as app: gr.Markdown("# 🔍 Reddit Sentiment Analyzer") with gr.Row(): subreddit = gr.Textbox(label="Subreddit (e.g., 'python')", value="all") num_posts = gr.Slider(1, 10, value=3, label="Number of Posts") btn = gr.Button("Analyze") output = gr.JSON(label="Results") btn.click(analyze_reddit, inputs=[subreddit, num_posts], outputs=output) app.launch()