import gradio as gr import uuid from datetime import datetime import random import os from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM import torch from huggingface_hub import login, HfApi # Token setup - Read from environment variables HF_TOKEN_READ = os.environ.get("HF_TOKEN_READ", "") HF_TOKEN_WRITE = os.environ.get("HF_TOKEN_WRITE", "") # Login with appropriate token if HF_TOKEN_READ: try: login(token=HF_TOKEN_READ) print("Logged in with read token") except Exception as e: print(f"Error logging in with read token: {e}") # Initialize HF API for write operations (if token is available) hf_api = None if HF_TOKEN_WRITE: try: hf_api = HfApi(token=HF_TOKEN_WRITE) print("HF API initialized with write token") except Exception as e: print(f"Error initializing HF API: {e}") # Model loading function with token support @gr.Cache() def load_model(model_name="microsoft/DialoGPT-medium"): """Load a Hugging Face model for text generation""" try: # Use read token if available token = HF_TOKEN_READ if HF_TOKEN_READ else None tokenizer = AutoTokenizer.from_pretrained( model_name, token=token, use_auth_token=token is not None ) if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token model = AutoModelForCausalLM.from_pretrained( model_name, token=token, use_auth_token=token is not None ) return tokenizer, model except Exception as e: print(f"Error loading model: {e}") return None, None # Save content to Hugging Face Hub (if write token is available) def save_to_hub(content, filename="social_content.txt", repo_id="your-username/social-media-content"): """Save generated content to Hugging Face Hub""" if not hf_api or not HF_TOKEN_WRITE: return "Write token not configured. Content not saved to Hub." try: # Create a temporary file with open(filename, "w") as f: f.write(content) # Upload to Hub hf_api.upload_file( path_or_fileobj=filename, path_in_repo=filename, repo_id=repo_id, repo_type="dataset", commit_message=f"Add social media content - {datetime.now().strftime('%Y-%m-%d %H:%M')}" ) # Clean up os.remove(filename) return f"Content saved to Hub: https://huggingface.co/datasets/{repo_id}" except Exception as e: return f"Error saving to Hub: {e}" # Fallback content generation def fallback_generate_content(prompt, platform): """Fallback content generation if AI models fail""" responses = { "Instagram": [ f"⨠{prompt.title()} āØ\n\nReady to transform your approach? Here's what you need to know:\n\nš„ Key insight that changes everything\nš” Pro tip that most people miss\nā” Action step you can take today\n\nWhat's your experience? Share in the comments! š", f"š Behind the scenes of {prompt} š\n\nSharing our process and what makes it special!\n\nEver wondered about {prompt}? Let us know your questions below! ā¬ļø", ], "TikTok": [ f"POV: You finally understand {prompt} š¤Æ\n\n*shows before and after*\n\nThe secret? [key insight]\n\nWho else needed to hear this? šŖ", f"Wait until you try this {prompt} hack! š\n\nGame changer alert! šØ\n\nSave this for later! ā¬ļø", ], "Both": [ f"Cross-platform content for {prompt} š±\n\nCreating value across different channels!\n\nWhat platform do you prefer? Let me know! š£ļø", ] } return random.choice(responses.get(platform, responses["Both"])) # AI-powered content generation def generate_content(prompt, platform, max_length=150): """Generate content using Hugging Face models""" try: # Load an appropriate model based on platform if platform == "Instagram": model_name = "microsoft/DialoGPT-medium" else: model_name = "gpt2" tokenizer, model = load_model(model_name) if tokenizer is None or model is None: return fallback_generate_content(prompt, platform) # Format prompt for better results formatted_prompt = f"Create engaging {platform} content about: {prompt}" # Generate content inputs = tokenizer.encode(formatted_prompt, return_tensors="pt") attention_mask = torch.ones(inputs.shape, dtype=torch.long) outputs = model.generate( inputs, max_length=max_length, num_return_sequences=1, temperature=0.8, do_sample=True, pad_token_id=tokenizer.eos_token_id, attention_mask=attention_mask ) generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True) # Clean up the output if generated_text.startswith(formatted_prompt): generated_text = generated_text[len(formatted_prompt):].strip() return generated_text if generated_text else fallback_generate_content(prompt, platform) except Exception as e: print(f"Error in generate_content: {e}") return fallback_generate_content(prompt, platform) # Improved hashtag generation def generate_hashtags(topic, platform): """Generate relevant hashtags using AI""" try: # Use read token if available token = HF_TOKEN_READ if HF_TOKEN_READ else None # Use a pipeline for text generation generator = pipeline( 'text-generation', model='gpt2', token=token, use_auth_token=token is not None ) prompt = f"Generate 5 relevant hashtags for {topic} on {platform}:" result = generator(prompt, max_length=50, num_return_sequences=1) hashtags = result[0]['generated_text'].replace(prompt, '').strip() # Clean up and format hashtags hashtag_list = [tag.strip().replace(' ', '') for tag in hashtags.split()[:5]] hashtags = ' '.join(['#' + tag for tag in hashtag_list if tag]) return hashtags if hashtags else fallback_hashtags(topic, platform) except Exception as e: print(f"Error generating hashtags: {e}") return fallback_hashtags(topic, platform) def fallback_hashtags(topic, platform): """Fallback hashtag generation""" base_hashtags = topic.lower().replace(' ', '').replace(',', ' #') if platform == "Instagram": platform_tags = "#instagood #photooftheday #instadaily #motivation #inspiration" elif platform == "TikTok": platform_tags = "#fyp #foryou #viral #trending #tiktok" else: platform_tags = "#content #socialmedia #digital" return f"#{base_hashtags} {platform_tags}" # Content improvement function def improve_content(content, platform, tone): """Improve existing content using AI""" try: # Use read token if available token = HF_TOKEN_READ if HF_TOKEN_READ else None improver = pipeline( 'text2text-generation', model='google/flan-t5-base', token=token, use_auth_token=token is not None ) prompt = f"Improve this {platform} content to make it more {tone}: {content}" result = improver(prompt, max_length=200) return result[0]['generated_text'] except Exception as e: print(f"Error improving content: {e}") return content # Main content generation function def generate_social_media_content(platform, content_type, topic, target_audience, tone, length, brand_voice, key_message, call_to_action, model_choice): """Generate social media content based on inputs""" # Generate main content content_prompt = f"Create a {content_type.lower()} for {platform} about {topic} targeting {target_audience} in a {tone.lower()} tone" generated_content = generate_content(content_prompt, platform) # Generate hashtags hashtags = generate_hashtags(topic, platform) # Calculate stats content_text = generated_content char_count = len(content_text) word_count = len(content_text.split()) # Platform-specific feedback platform_feedback = "" if platform == "Instagram": if char_count > 2200: platform_feedback = "ā ļø Caption may be too long for Instagram" else: platform_feedback = "ā Good length for Instagram" elif platform == "TikTok": if char_count > 150: platform_feedback = "ā ļø Consider shorter text for TikTok" else: platform_feedback = "ā Perfect for TikTok" # Format output output = f""" # {content_type} for {platform} ## Content: {generated_content} ## Hashtags: {hashtags} ## Stats: - Characters: {char_count} - Words: {word_count} - {platform_feedback} ## Details: - Target: {target_audience} - Tone: {tone} - CTA: {call_to_action} - AI Model: {model_choice} - Created: {datetime.now().strftime('%Y-%m-%d %H:%M')} """ return output def get_trending_topics(): """Get trending topic suggestions""" trending = [ "Productivity hacks", "Morning routine", "Self care Sunday", "Workspace setup", "Healthy recipes", "Weekend vibes", "Goal setting", "Mindfulness tips" ] return random.choice(trending) def load_template(platform, template_name): """Load a content template""" templates = { "Instagram": { "Product Showcase": { "template": "š Introducing [PRODUCT NAME] š\n\n[KEY BENEFIT] that [SOLVES PROBLEM]\n\n⨠Perfect for [TARGET AUDIENCE]\nš« [UNIQUE FEATURE]\nšÆ [CALL TO ACTION]\n\n[HASHTAGS]", "example": "š Introducing our New Workout Planner š\n\nStay organized and motivated with our 90-day fitness tracker\n\n⨠Perfect for busy professionals\nš« Includes meal planning section\nšÆ Link in bio to get yours!\n\n#fitness #workout #planning" }, "Behind the Scenes": { "template": "Behind the scenes at [LOCATION/EVENT] š\n\n[WHAT'S HAPPENING]\n\n[INTERESTING DETAIL]\n\nWhat would you like to see more of?\n\n[HASHTAGS]", "example": "Behind the scenes at our studio today š\n\nCreating content for our new product launch\n\nOur team worked 12 hours straight but the energy was amazing!\n\nWhat would you like to see more of?\n\n#behindthescenes #teamwork #creative" } }, "TikTok": { "Tutorial": { "template": "How to [SKILL/TASK] in [TIME] ā°\n\nStep 1: [ACTION]\nStep 2: [ACTION] \nStep 3: [ACTION]\n\nTry it and let me know! šŖ\n\n[HASHTAGS]", "example": "How to meal prep in 30 minutes ā°\n\nStep 1: Choose 3 proteins\nStep 2: Prep all veggies first\nStep 3: Cook everything at once\n\nTry it and let me know! šŖ\n\n#mealprep #cooking #lifehacks" }, "Trending Challenge": { "template": "[TREND] but make it [YOUR NICHE] āØ\n\n[YOUR TWIST ON THE TREND]\n\nWho else does this? š\n\n[HASHTAGS]", "example": "Tell me you're a plant parent without telling me āØ\n\nMe: Has 47 plants and knows each one's watering schedule by heart\n\nWho else does this? š\n\n#plantparent #planttok #relatable" } } } if platform in templates and template_name in templates[platform]: return f"### {template_name} Template for {platform}\n\n```\n{templates[platform][template_name]['template']}\n```\n\n#### Example:\n{templates[platform][template_name]['example']}" return "Template not found" # Gradio interface with gr.Blocks( title="Social Media Content Creator", theme=gr.themes.Soft(), css=""" .gradio-container { max-width: 1200px !important; } .output-markdown { padding: 20px; border-radius: 10px; background: #f8f9fa; border-left: 4px solid #667eea; } .header { text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px; margin-bottom: 20px; } .token-status { padding: 10px; border-radius: 5px; margin-bottom: 10px; } .token-ok { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; } .token-warning { background: #fff3cd; color: #856404; border: 1px solid #ffeeba; } """ ) as demo: with gr.Column(): gr.Markdown("""
Create engaging content for Instagram and TikTok with AI assistance