Spaces:
Sleeping
Sleeping
Update tweet_analyzer.py
Browse files12343 unmodified lines89101112131 unmodified line15161718192051 unmodified lines72737475767778798081828384858687888990919293949543 unmodified lines139140141142143144145146147148149150151152import osfrom PyPDF2 import PdfReaderimport pandas as pdfrom dotenv import load_dotenv3 unmodified linesfrom sklearn.decomposition import NMFfrom sklearn.feature_extraction.text import TfidfVectorizerimport randomclass TweetDatasetProcessor:def __init__(self):1 unmodified lineself.groq_client = groq.Groq(api_key=os.getenv('Groq_api'))self.tweets = []self.personality_profile = {}def extract_text_from_pdf(self, pdf_path):"""Extract text content from PDF file."""51 unmodified lines"""Extract hashtags from tweet."""return [word for word in text.split() if word.startswith('#')]def analyze_personality(self):"""Comprehensive personality analysis."""all_tweets = [tweet['content'] for tweet in self.tweets]analysis_prompt = f"""Perform a deep psychological analysis of the author based on these tweets. Analyze:Core beliefs, emotional tendencies, cognitive patterns, etc.Tweets for analysis:{json.dumps(all_tweets[:30], indent=2)}"""response = self.groq_client.chat.completions.create(messages=[{"role": "system", "content": "You are an expert psychologist."},{"role": "user", "content": analysis_prompt},],model="llama-3.1-70b-versatile",temperature=0.1,)self.personality_profile = response.choices[0].message.contentreturn self.personality_profiledef analyze_topics(self, n_topics=5):43 unmodified lines4. Includes relevant mentions or hashtags if applicable.The tweet should feel diverse and authentic, touching on a variety of topics."""response = self.groq_client.chat.completions.create(messages=[{"role": "system", "content": "You are an expert in replicating writing and thinking patterns."},{"role": "user", "content": generation_prompt},],model="llama-3.1-70b-versatile",temperature=1.0, # Increased temperature for more diversitymax_tokens=150,)return response.choices[0].message.content12343 unmodified lines8910111213141 unmodified line1617181920212251 unmodified lines747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811943 unmodified lines163164165166167168169170171172173174175176177178179import osfrom PyPDF2 import PdfReaderimport pandas as pdfrom dotenv import load_dotenv3 unmodified linesfrom sklearn.decomposition import NMFfrom sklearn.feature_extraction.text import TfidfVectorizerimport randomfrom transformers import GPT2Tokenizerclass TweetDatasetProcessor:def __init__(self):1 unmodified lineself.groq_client = groq.Groq(api_key=os.getenv('Groq_api'))self.tweets = []self.personality_profile = {}self.tokenizer = GPT2Tokenizer.from_pretrained('gpt2') # Initialize tokenizerdef extract_text_from_pdf(self, pdf_path):"""Extract text content from PDF file."""51 unmodified lines"""Extract hashtags from tweet."""return [word for word in text.split() if word.startswith('#')]def truncate_to_token_limit(self, tweets, max_tokens=6000):"""Truncate tweets to fit within token limit."""total_tokens = 0truncated_tweets = []for tweet in tweets:tokens = self.tokenizer.encode(tweet)if total_tokens + len(tokens) > max_tokens:breaktotal_tokens += len(tokens)truncated_tweets.append(tweet)return truncated_tweetsdef analyze_personality(self):"""Comprehensive personality analysis."""all_tweets = [tweet['content'] for tweet in self.tweets]# Truncate tweets to avoid exceeding token limittruncated_tweets = self.truncate_to_token_limit(all_tweets, max_tokens=6000)# Create analysis prompt with truncated tweetsanalysis_prompt = f"""Perform a deep psychological analysis of the author based on these tweets. Analyze:Core beliefs, emotional tendencies, cognitive patterns, etc.Tweets for analysis:{json.dumps(truncated_tweets, indent=2)}"""try:response = self.groq_client.chat.completions.create(messages=[{"role": "system", "content": "You are an expert psychologist."},{"role": "user", "content": analysis_prompt},],model="llama-3.1-70b-versatile",temperature=0.1,)self.personality_profile = response.choices[0].message.contentexcept Exception as e:print(f"Error processing personality analysis: {e}")self.personality_profile = {}return self.personality_profiledef analyze_topics(self, n_topics=5):43 unmodified lines4. Includes relevant mentions or hashtags if applicable.The tweet should feel diverse and authentic, touching on a variety of topics."""try:response = self.groq_client.chat.completions.create(messages=[{"role": "system", "content": "You are an expert in replicating writing and thinking patterns."},{"role": "user", "content": generation_prompt},],model="llama-3.1-70b-versatile",temperature=1.0, # Increased temperature for more diversitymax_tokens=150,)return response.choices[0].message.contentexcept Exception as e:print(f"Error generating tweet: {e}")return "Error generating tweet"
tweet_analyzer.py+49-22