CoolFace
Apppublic

d221/Linkedin_Content_Generator

sourceHugging Facemitupdated 2y agoView on Hugging Face
3likes
post_generator.py91 linesDownload Raw Back to root
1from langchain_groq import ChatGroq2import os3from dotenv import load_dotenv4import pandas as pd5import json6 7class FewShotPosts:8    def __init__(self, file_path="processed_posts.json"):9        self.df = None10        self.unique_tags = None11        self.load_posts(file_path)12 13    def load_posts(self, file_path):14        with open(file_path, encoding="utf-8") as f:15            posts = json.load(f)16            self.df = pd.json_normalize(posts)17            self.df['length'] = self.df['line_count'].apply(self.categorize_length)18            all_tags = self.df['tags'].apply(lambda x: x).sum()19            self.unique_tags = list(set(all_tags))20 21    def get_filtered_posts(self, length, language, tag):22        df_filtered = self.df[23            (self.df['tags'].apply(lambda tags: tag in tags)) &24            (self.df['language'] == language) &25            (self.df['length'] == length)26        ]27        return df_filtered.to_dict(orient='records')28 29    def categorize_length(self, line_count):30        if line_count < 5:31            return "Short"32        elif 5 <= line_count <= 10:33            return "Medium"34        else:35            return "Long"36 37    def get_tags(self):38        return self.unique_tags39 40load_dotenv()41few_shot = FewShotPosts()42 43def get_length_str(length):44    if length == "Short":45        return "1 to 5 lines"46    elif length == "Medium":47        return "6 to 10 lines"48    elif length == "Long":49        return "11 to 15 lines"50    elif length == "Extra Long":51        return "16 to 20 lines"52    else:53        return "6 to 10 lines"54 55def generate_post(length, language, tag, model_name="llama-3.3-70b-versatile", custom_context=""):56    prompt = get_prompt(length, language, tag, custom_context)57    llm_instance = ChatGroq(groq_api_key=os.getenv("GROQ_API_KEY"), model_name=model_name)58    response = llm_instance.invoke(prompt)59    return response.content60 61def get_prompt(length, language, tag, custom_context=""):62    length_str = get_length_str(length)63 64    prompt = f"""65    Generate a LinkedIn post using the below information. No preamble.66    1) Topic: {tag}67    2) Length: {length_str}68    3) Language: {language}69    If Language is Hinglish then it means it is a mix of Hindi and English. 70    The script for the generated post should always be English.71    """72 73    # Add custom context if provided74    if custom_context.strip():75        prompt += f"\nUse the following additional knowledge or context about the topic:\n{custom_context}\n"76 77    # Optionally include few-shot examples78    examples = few_shot.get_filtered_posts(length, language, tag)79    if len(examples) > 0:80        prompt += "\n4) Use the writing style as per the following examples:"81        for i, post in enumerate(examples):82            post_text = post['text']83            prompt += f"\n\nExample {i+1}:\n{post_text}"84            if i == 1:  # limit to 2 examples85                break86 87    return prompt88 89if __name__ == "__main__":90    print(generate_post("Medium", "English", "Mental Health", custom_context="Remember to mention the importance of daily meditation."))91