Spaces:
Build error
Build error
Update app.py
#1
by Manasa1 - opened
8 unmodified lines910111213141516171816 unmodified lines35363738394070 unmodified lines1111121131141151161171181191201211221231241251261271281291301311321331348 unmodified linesload_dotenv()class TweetDatasetProcessor:def __init__(self, fine_tuned_model_name, pdf_path):self.tweets = []self.personality_profile = {}self.vectorizer = None # No need for vectorizer here since we're not clusteringself.used_tweets = set() # Track used tweets to avoid repetitionself.pdf_path = pdf_path16 unmodified linesdef extract_text_from_pdf(self):"""Extract text content from PDF file."""reader = PdfReader(self.pdf_path)text = ""for page in reader.pages:70 unmodified linesreturn generated_tweet# Gradio Interface Functiondef gradio_interface():# Path to the PDF with tweetspdf_path = 'Dataset (4).pdf' # Replace with your PDF file pathfine_tuned_model_name = 'Manasa1/GPT2_Finetuned_tweets' # Replace with the path to your fine-tuned modelprocessor = TweetDatasetProcessor(fine_tuned_model_name, pdf_path)text = processor.extract_text_from_pdf()tweets = processor.process_pdf_content(text)personality_analysis = processor.analyze_personality(max_tweets=50)generated_tweet = processor.generate_tweet(context="AI-powered tweet generation", sample_size=3)return personality_analysis, generated_tweet# Gradio app setupiface = gr.Interface(fn=gradio_interface,inputs=[],outputs=[gr.Textbox(label="Personality Analysis"),gr.Textbox(label="Generated Tweet")8 unmodified lines9101112131415161716 unmodified lines343536373839404170 unmodified lines1121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414428 unmodified linesload_dotenv()class TweetDatasetProcessor:def __init__(self, fine_tuned_model_name, pdf_path=None):self.tweets = []self.personality_profile = {}self.used_tweets = set() # Track used tweets to avoid repetitionself.pdf_path = pdf_path16 unmodified linesdef extract_text_from_pdf(self):"""Extract text content from PDF file."""if not self.pdf_path:return ""reader = PdfReader(self.pdf_path)text = ""for page in reader.pages:70 unmodified linesreturn generated_tweet# Gradio Interface Functiondef gradio_interface(pdf_file, context="AI-powered tweet generation"):# Initialize the processor with uploaded PDF pathfine_tuned_model_name = 'Manasa1/GPT2_Finetuned_tweets' # Replace with the path to your fine-tuned modelprocessor = TweetDatasetProcessor(fine_tuned_model_name, pdf_path=pdf_file.name)# Extract text from PDF and process ittext = processor.extract_text_from_pdf()tweets = processor.process_pdf_content(text)# Analyze personality based on tweetspersonality_analysis = processor.analyze_personality(max_tweets=50)# Generate tweet based on the personality analysis and contextgenerated_tweet = processor.generate_tweet(context=context, sample_size=3)return personality_analysis, generated_tweet# Gradio app setupiface = gr.Interface(fn=gradio_interface,inputs=[gr.File(label="Upload PDF with Tweets"),gr.Textbox(label="Context for Tweet Generation (optional)", placeholder="e.g., AI-powered tweet generation")],outputs=[gr.Textbox(label="Personality Analysis"),gr.Textbox(label="Generated Tweet")],live=True,title="AI Personality and Tweet Generation",description="Automatically analyze personality and generate tweets based on a provided PDF of tweets.")# Launch the appif __name__ == "__main__":iface.launch()import gradio as grfrom transformers import AutoModelForCausalLM, AutoTokenizerimport randomfrom datetime import datetimefrom PyPDF2 import PdfReaderimport jsonfrom dotenv import load_dotenvload_dotenv()class TweetDatasetProcessor:def __init__(self, fine_tuned_model_name, pdf_path=None):self.tweets = []self.personality_profile = {}self.used_tweets = set() # Track used tweets to avoid repetitionself.pdf_path = pdf_path# Load fine-tuned model and tokenizerself.model = AutoModelForCausalLM.from_pretrained(fine_tuned_model_name)self.tokenizer = AutoTokenizer.from_pretrained(fine_tuned_model_name)@staticmethoddef _process_line(line):"""Process a single line."""line = line.strip()if not line or line.startswith('http'): # Skip empty lines and URLsreturn Nonereturn {'content': line,'timestamp': datetime.now(),'mentions': [word for word in line.split() if word.startswith('@')],'hashtags': [word for word in line.split() if word.startswith('#')]}def extract_text_from_pdf(self):"""Extract text content from PDF file."""if not self.pdf_path:return ""reader = PdfReader(self.pdf_path)text = ""for page in reader.pages:text += page.extract_text()return textdef process_pdf_content(self, text):"""Process PDF content and clean extracted tweets."""if not text.strip():raise ValueError("The provided PDF appears to be empty.")lines = text.split('\n')clean_tweets = [TweetDatasetProcessor._process_line(line) for line in lines]self.tweets = [tweet for tweet in clean_tweets if tweet]if not self.tweets:raise ValueError("No tweets were extracted from the PDF. Ensure the content is properly formatted.")return self.tweetsdef analyze_personality(self, max_tweets=50):"""Comprehensive personality analysis using a limited subset of tweets."""if not self.tweets:raise ValueError("No tweets available for personality analysis.")all_tweets = [tweet['content'] for tweet in self.tweets][:max_tweets]analysis_prompt = f"""Perform a deep psychological analysis of the author based on these tweets:Core beliefs, emotional tendencies, cognitive patterns, etc.Tweets for analysis:{json.dumps(all_tweets, indent=2)}"""input_ids = self.tokenizer.encode(analysis_prompt, return_tensors='pt')output = self.model.generate(input_ids, max_length=500, num_return_sequences=1, temperature=0.7)personality_analysis = self.tokenizer.decode(output[0], skip_special_tokens=True)self.personality_profile = personality_analysisreturn self.personality_profiledef generate_tweet(self, context="", sample_size=3):"""Generate a new tweet by sampling random tweets and avoiding repetition."""if not self.tweets:return "Error: No tweets available for generation."# Randomly sample unique tweetsavailable_tweets = [tweet for tweet in self.tweets if tweet['content'] not in self.used_tweets]if len(available_tweets) < sample_size:self.used_tweets.clear() # Reset used tweets if all have been usedavailable_tweets = self.tweetssampled_tweets = random.sample(available_tweets, sample_size)sampled_contents = [tweet['content'] for tweet in sampled_tweets]# Update the used tweets trackerself.used_tweets.update(sampled_contents)# Truncate personality profile to avoid token overflowpersonality_profile_excerpt = self.personality_profile[:400] if len(self.personality_profile) > 400 else self.personality_profile# Construct the promptprompt = f"""Based on this personality profile:{personality_profile_excerpt}Current context or topic (if any):{context}Tweets for context:{', '.join(sampled_contents)}**Only generate the tweet. Do not include analysis, explanation, or any other content.**"""input_ids = self.tokenizer.encode(prompt, return_tensors='pt')output = self.model.generate(input_ids, max_length=150, num_return_sequences=1, temperature=1.0)generated_tweet = self.tokenizer.decode(output[0], skip_special_tokens=True).strip()return generated_tweet# Gradio Interface Functiondef gradio_interface(pdf_file, context="AI-powered tweet generation"):# Initialize the processor with uploaded PDF pathfine_tuned_model_name = 'Manasa1/GPT2_Finetuned_tweets' # Replace with the path to your fine-tuned modelprocessor = TweetDatasetProcessor(fine_tuned_model_name, pdf_path=pdf_file.name)# Extract text from PDF and process ittext = processor.extract_text_from_pdf()tweets = processor.process_pdf_content(text)# Analyze personality based on tweetspersonality_analysis = processor.analyze_personality(max_tweets=50)# Generate tweet based on the personality analysis and contextgenerated_tweet = processor.generate_tweet(context=context, sample_size=3)return personality_analysis, generated_tweet# Gradio app setupiface = gr.Interface(fn=gradio_interface,inputs=[gr.File(label="Upload PDF with Tweets"),gr.Textbox(label="Context for Tweet Generation (optional)", placeholder="e.g., AI-powered tweet generation")],outputs=[gr.Textbox(label="Personality Analysis"),gr.Textbox(label="Generated Tweet")],live=True,title="AI Personality and Tweet Generation",description="Automatically analyze personality and generate tweets based on a provided PDF of tweets.")# Launch the appif __name__ == "__main__":iface.launch()import gradio as grfrom transformers import AutoModelForCausalLM, AutoTokenizerimport randomfrom datetime import datetimefrom PyPDF2 import PdfReaderimport jsonfrom dotenv import load_dotenvload_dotenv()class TweetDatasetProcessor:def __init__(self, fine_tuned_model_name, pdf_path=None):self.tweets = []self.personality_profile = {}self.used_tweets = set() # Track used tweets to avoid repetitionself.pdf_path = pdf_path# Load fine-tuned model and tokenizerself.model = AutoModelForCausalLM.from_pretrained(fine_tuned_model_name)self.tokenizer = AutoTokenizer.from_pretrained(fine_tuned_model_name)@staticmethoddef _process_line(line):"""Process a single line."""line = line.strip()if not line or line.startswith('http'): # Skip empty lines and URLsreturn Nonereturn {'content': line,'timestamp': datetime.now(),'mentions': [word for word in line.split() if word.startswith('@')],'hashtags': [word for word in line.split() if word.startswith('#')]}def extract_text_from_pdf(self):"""Extract text content from PDF file."""if not self.pdf_path:return ""reader = PdfReader(self.pdf_path)text = ""for page in reader.pages:text += page.extract_text()return textdef process_pdf_content(self, text):"""Process PDF content and clean extracted tweets."""if not text.strip():raise ValueError("The provided PDF appears to be empty.")lines = text.split('\n')clean_tweets = [TweetDatasetProcessor._process_line(line) for line in lines]self.tweets = [tweet for tweet in clean_tweets if tweet]if not self.tweets:raise ValueError("No tweets were extracted from the PDF. Ensure the content is properly formatted.")return self.tweetsdef analyze_personality(self, max_tweets=50):"""Comprehensive personality analysis using a limited subset of tweets."""if not self.tweets:raise ValueError("No tweets available for personality analysis.")all_tweets = [tweet['content'] for tweet in self.tweets][:max_tweets]analysis_prompt = f"""Perform a deep psychological analysis of the author based on these tweets:Core beliefs, emotional tendencies, cognitive patterns, etc.Tweets for analysis:{json.dumps(all_tweets, indent=2)}"""input_ids = self.tokenizer.encode(analysis_prompt, return_tensors='pt')output = self.model.generate(input_ids, max_length=500, num_return_sequences=1, temperature=0.7)personality_analysis = self.tokenizer.decode(output[0], skip_special_tokens=True)self.personality_profile = personality_analysisreturn self.personality_profiledef generate_tweet(self, context="", sample_size=3):"""Generate a new tweet by sampling random tweets and avoiding repetition."""if not self.tweets:return "Error: No tweets available for generation."# Randomly sample unique tweetsavailable_tweets = [tweet for tweet in self.tweets if tweet['content'] not in self.used_tweets]if len(available_tweets) < sample_size:self.used_tweets.clear() # Reset used tweets if all have been usedavailable_tweets = self.tweetssampled_tweets = random.sample(available_tweets, sample_size)sampled_contents = [tweet['content'] for tweet in sampled_tweets]# Update the used tweets trackerself.used_tweets.update(sampled_contents)# Truncate personality profile to avoid token overflowpersonality_profile_excerpt = self.personality_profile[:400] if len(self.personality_profile) > 400 else self.personality_profile# Construct the promptprompt = f"""Based on this personality profile:{personality_profile_excerpt}Current context or topic (if any):{context}Tweets for context:{', '.join(sampled_contents)}**Only generate the tweet. Do not include analysis, explanation, or any other content.**"""input_ids = self.tokenizer.encode(prompt, return_tensors='pt')output = self.model.generate(input_ids, max_length=150, num_return_sequences=1, temperature=1.0)generated_tweet = self.tokenizer.decode(output[0], skip_special_tokens=True).strip()return generated_tweet# Gradio Interface Functiondef gradio_interface(pdf_file, context="AI-powered tweet generation"):# Initialize the processor with uploaded PDF pathfine_tuned_model_name = 'Manasa1/GPT2_Finetuned_tweets' # Replace with the path to your fine-tuned modelpdf_path = 'Dataset (4).pdf'processor = TweetDatasetProcessor(fine_tuned_model_name, pdf_path=pdf_path)# Extract text from PDF and process ittext = processor.extract_text_from_pdf()tweets = processor.process_pdf_content(text)# Analyze personality based on tweetspersonality_analysis = processor.analyze_personality(max_tweets=50)# Generate tweet based on the personality analysis and contextgenerated_tweet = processor.generate_tweet(context=context, sample_size=3)return personality_analysis, generated_tweet# Gradio app setupiface = gr.Interface(fn=gradio_interface,inputs=[gr.File(label="Upload PDF with Tweets"),gr.Textbox(label="Context for Tweet Generation (optional)", placeholder="e.g., AI-powered tweet generation")],outputs=[gr.Textbox(label="Personality Analysis"),gr.Textbox(label="Generated Tweet")
app.py+316-8