Spaces:
Sleeping
Sleeping
Delete tweet_analyzer.py
Browse files- tweet_analyzer.py +0 -130
tweet_analyzer.py
DELETED
@@ -1,130 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
from PyPDF2 import PdfReader
|
3 |
-
import pandas as pd
|
4 |
-
from dotenv import load_dotenv
|
5 |
-
import json
|
6 |
-
from datetime import datetime
|
7 |
-
from sklearn.feature_extraction.text import TfidfVectorizer
|
8 |
-
from sklearn.cluster import KMeans
|
9 |
-
import random
|
10 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
11 |
-
import torch
|
12 |
-
|
13 |
-
class TweetDatasetProcessor:
|
14 |
-
def __init__(self, fine_tuned_model_name):
|
15 |
-
load_dotenv()
|
16 |
-
self.tweets = []
|
17 |
-
self.personality_profile = {}
|
18 |
-
self.vectorizer = TfidfVectorizer(stop_words='english')
|
19 |
-
self.used_tweets = set() # Track used tweets to avoid repetition
|
20 |
-
|
21 |
-
# Load fine-tuned model and tokenizer
|
22 |
-
self.model = AutoModelForCausalLM.from_pretrained(fine_tuned_model_name)
|
23 |
-
self.tokenizer = AutoTokenizer.from_pretrained(fine_tuned_model_name)
|
24 |
-
|
25 |
-
@staticmethod
|
26 |
-
def _process_line(line):
|
27 |
-
"""Process a single line."""
|
28 |
-
line = line.strip()
|
29 |
-
if not line or line.startswith('http'): # Skip empty lines and URLs
|
30 |
-
return None
|
31 |
-
return {
|
32 |
-
'content': line,
|
33 |
-
'timestamp': datetime.now(),
|
34 |
-
'mentions': [word for word in line.split() if word.startswith('@')],
|
35 |
-
'hashtags': [word for word in line.split() if word.startswith('#')]
|
36 |
-
}
|
37 |
-
|
38 |
-
def extract_text_from_pdf(self, pdf_path):
|
39 |
-
"""Extract text content from PDF file."""
|
40 |
-
reader = PdfReader(pdf_path)
|
41 |
-
text = ""
|
42 |
-
for page in reader.pages:
|
43 |
-
text += page.extract_text()
|
44 |
-
return text
|
45 |
-
|
46 |
-
def process_pdf_content(self, text):
|
47 |
-
"""Process PDF content and clean extracted tweets."""
|
48 |
-
if not text.strip():
|
49 |
-
raise ValueError("The uploaded PDF appears to be empty.")
|
50 |
-
|
51 |
-
lines = text.split('\n')
|
52 |
-
clean_tweets = [TweetDatasetProcessor._process_line(line) for line in lines]
|
53 |
-
self.tweets = [tweet for tweet in clean_tweets if tweet]
|
54 |
-
|
55 |
-
if not self.tweets:
|
56 |
-
raise ValueError("No tweets were extracted from the PDF. Ensure the content is properly formatted.")
|
57 |
-
|
58 |
-
# Save the processed tweets to a CSV
|
59 |
-
df = pd.DataFrame(self.tweets)
|
60 |
-
df.to_csv('processed_tweets.csv', index=False)
|
61 |
-
return df
|
62 |
-
|
63 |
-
def categorize_tweets(self):
|
64 |
-
"""Cluster tweets into categories using KMeans."""
|
65 |
-
all_tweets = [tweet['content'] for tweet in self.tweets]
|
66 |
-
if not all_tweets:
|
67 |
-
raise ValueError("No tweets available for clustering.")
|
68 |
-
|
69 |
-
tfidf_matrix = self.vectorizer.fit_transform(all_tweets)
|
70 |
-
kmeans = KMeans(n_clusters=5, random_state=1)
|
71 |
-
kmeans.fit(tfidf_matrix)
|
72 |
-
|
73 |
-
for i, tweet in enumerate(self.tweets):
|
74 |
-
tweet['category'] = f"Category {kmeans.labels_[i]}"
|
75 |
-
return pd.DataFrame(self.tweets)
|
76 |
-
|
77 |
-
def analyze_personality(self, max_tweets=50):
|
78 |
-
"""Comprehensive personality analysis using a limited subset of tweets."""
|
79 |
-
if not self.tweets:
|
80 |
-
raise ValueError("No tweets available for personality analysis.")
|
81 |
-
|
82 |
-
all_tweets = [tweet['content'] for tweet in self.tweets][:max_tweets]
|
83 |
-
analysis_prompt = f"""Perform a deep psychological analysis of the author based on these tweets:
|
84 |
-
Core beliefs, emotional tendencies, cognitive patterns, etc.
|
85 |
-
Tweets for analysis:
|
86 |
-
{json.dumps(all_tweets, indent=2)}
|
87 |
-
"""
|
88 |
-
|
89 |
-
input_ids = self.tokenizer.encode(analysis_prompt, return_tensors='pt')
|
90 |
-
output = self.model.generate(input_ids, max_length=500, num_return_sequences=1, temperature=0.7)
|
91 |
-
personality_analysis = self.tokenizer.decode(output[0], skip_special_tokens=True)
|
92 |
-
|
93 |
-
self.personality_profile = personality_analysis
|
94 |
-
return self.personality_profile
|
95 |
-
|
96 |
-
def generate_tweet(self, context="", sample_size=3):
|
97 |
-
"""Generate a new tweet by sampling random tweets and avoiding repetition."""
|
98 |
-
if not self.tweets:
|
99 |
-
return "Error: No tweets available for generation."
|
100 |
-
|
101 |
-
# Randomly sample unique tweets
|
102 |
-
available_tweets = [tweet for tweet in self.tweets if tweet['content'] not in self.used_tweets]
|
103 |
-
if len(available_tweets) < sample_size:
|
104 |
-
self.used_tweets.clear() # Reset used tweets if all have been used
|
105 |
-
available_tweets = self.tweets
|
106 |
-
|
107 |
-
sampled_tweets = random.sample(available_tweets, sample_size)
|
108 |
-
sampled_contents = [tweet['content'] for tweet in sampled_tweets]
|
109 |
-
|
110 |
-
# Update the used tweets tracker
|
111 |
-
self.used_tweets.update(sampled_contents)
|
112 |
-
|
113 |
-
# Truncate personality profile to avoid token overflow
|
114 |
-
personality_profile_excerpt = self.personality_profile[:400] if len(self.personality_profile) > 400 else self.personality_profile
|
115 |
-
|
116 |
-
# Construct the prompt
|
117 |
-
prompt = f"""Based on this personality profile:
|
118 |
-
{personality_profile_excerpt}
|
119 |
-
Current context or topic (if any):
|
120 |
-
{context}
|
121 |
-
Tweets for context:
|
122 |
-
{', '.join(sampled_contents)}
|
123 |
-
**Only generate the tweet. Do not include analysis, explanation, or any other content.**
|
124 |
-
"""
|
125 |
-
|
126 |
-
input_ids = self.tokenizer.encode(prompt, return_tensors='pt')
|
127 |
-
output = self.model.generate(input_ids, max_length=150, num_return_sequences=1, temperature=1.0)
|
128 |
-
generated_tweet = self.tokenizer.decode(output[0], skip_special_tokens=True).strip()
|
129 |
-
|
130 |
-
return generated_tweet
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|