Facebook AI Writer features like post and story generator

This commit is contained in:
ajaysi
2025-04-10 15:24:00 +05:30
parent 8ac2095ac4
commit b556edb989
8 changed files with 763 additions and 136 deletions

View File

@@ -0,0 +1,266 @@
"""
Facebook AI Writer
This module provides a comprehensive suite of tools for generating Facebook content.
"""
import time
import os
import json
import requests
import streamlit as st
import importlib
import sys
from pathlib import Path
from ...gpt_providers.text_generation.main_text_generation import llm_text_gen
from .modules.post_generator import write_fb_post
from .modules.story_generator import write_fb_story
from .modules.reel_generator import write_fb_reel
from .modules.carousel_generator import write_fb_carousel
from .modules.event_generator import write_fb_event
from .modules.group_post_generator import write_fb_group_post
from .modules.page_about_generator import write_fb_page_about
from .modules.ad_copy_generator import write_fb_ad_copy
from .modules.hashtag_generator import write_fb_hashtags
from .modules.engagement_analyzer import analyze_fb_engagement
#from streamlit_quill import st_quill
def generate_facebook_post(business_type, target_audience, post_goal, post_tone, include, avoid):
"""
Generates a Facebook post prompt for an LLM based on user input.
"""
prompt = f"""
I am a {business_type} looking to engage my target audience, {target_audience}, on Facebook.
My goal for this detailed post is: {post_goal}. The tone should be {post_tone}.
Here are some additional preferences:
- **Include:** {include}
- **Avoid:** {avoid}
Please write a well-structured Facebook post with:
1. A **catchy opening** to grab attention.
2. Detailed **Engaging content** that highlights key benefits or features.
3. A **strong call-to-action** (CTA) encouraging my audience to take action.
4. If applicable, suggest **multimedia** (images, videos, etc.).
5. Include **relevant hashtags** for visibility.
"""
try:
response = llm_text_gen(prompt)
return response
except Exception as err:
st.error(f"An error occurred while generating the prompt: {err}")
return None
def facebook_main_menu():
"""Main function for the Facebook AI Writer."""
# Initialize session state for selected tool if it doesn't exist
if "selected_tool" not in st.session_state:
st.session_state.selected_tool = None
# Define the Facebook tools with their details
facebook_tools = [
# Content Creation Tools
{
"name": "FB Post Generator",
"icon": "📝",
"description": "Create engaging Facebook posts that drive engagement and reach.",
"color": "#1877F2", # Facebook blue
"category": "Content Creation",
"function": write_fb_post,
"status": "active"
},
{
"name": "FB Story Generator",
"icon": "📱",
"description": "Generate creative Facebook Stories with text overlays and engagement elements.",
"color": "#1877F2",
"category": "Content Creation",
"function": write_fb_story,
"status": "active"
},
{
"name": "FB Reel Generator",
"icon": "🎥",
"description": "Create engaging Facebook Reels scripts with trending music suggestions.",
"color": "#1877F2",
"category": "Content Creation",
"function": write_fb_reel,
"status": "active"
},
{
"name": "Carousel Generator",
"icon": "🔄",
"description": "Generate multi-image carousel posts with engaging captions for each slide.",
"color": "#1877F2",
"category": "Content Creation",
"function": write_fb_carousel,
"status": "active"
},
# Business Tools
{
"name": "Event Description Generator",
"icon": "📅",
"description": "Create compelling event descriptions that drive attendance and engagement.",
"color": "#1877F2",
"category": "Business Tools",
"function": write_fb_event,
"status": "active"
},
{
"name": "Group Post Generator",
"icon": "👥",
"description": "Generate engaging posts for Facebook Groups with community-focused content.",
"color": "#1877F2",
"category": "Business Tools",
"function": write_fb_group_post,
"status": "active"
},
{
"name": "Page About Generator",
"icon": "",
"description": "Create professional and engaging About sections for your Facebook Page.",
"color": "#1877F2",
"category": "Business Tools",
"function": write_fb_page_about,
"status": "active"
},
# Marketing Tools
{
"name": "Ad Copy Generator",
"icon": "💰",
"description": "Generate high-converting ad copy for Facebook Ads with targeting suggestions.",
"color": "#1877F2",
"category": "Marketing Tools",
"function": write_fb_ad_copy,
"status": "active"
},
{
"name": "Hashtag Generator",
"icon": "#️⃣",
"description": "Generate trending and relevant hashtags for your Facebook content.",
"color": "#1877F2",
"category": "Marketing Tools",
"function": write_fb_hashtags,
"status": "active"
},
{
"name": "Engagement Analyzer",
"icon": "📊",
"description": "Analyze your content performance and get AI-powered improvement suggestions.",
"color": "#1877F2",
"category": "Marketing Tools",
"function": analyze_fb_engagement,
"status": "active"
},
# Future Tools
{
"name": "Content Calendar",
"icon": "📅",
"description": "Plan and organize your Facebook content with AI-powered scheduling suggestions.",
"color": "#1877F2",
"category": "Future Tools",
"function": None,
"status": "future"
},
{
"name": "Live Stream Script",
"icon": "🎥",
"description": "Generate engaging scripts for Facebook Live streams with audience interaction points.",
"color": "#1877F2",
"category": "Future Tools",
"function": None,
"status": "future"
}
]
# Create a container for the dashboard
dashboard_container = st.container()
# Create a container for the tool input section
tool_container = st.container()
# If a tool is selected, show its input section
if st.session_state.selected_tool is not None:
with tool_container:
# Display the selected tool's input section
st.markdown("---")
st.markdown(f"# {st.session_state.selected_tool['icon']} {st.session_state.selected_tool['name']}")
# Add a back button
if st.button("← Back to Dashboard", key="back_to_dashboard"):
# Clear the selected tool from session state
st.session_state.selected_tool = None
st.rerun()
# Call the function for the selected tool
if st.session_state.selected_tool["function"]:
st.session_state.selected_tool["function"]()
else:
# Display coming soon or future tool information
st.info(f"**{st.session_state.selected_tool['status'].replace('_', ' ').title()}!**")
st.write(st.session_state.selected_tool["description"])
st.image(f"https://via.placeholder.com/600x300?text={st.session_state.selected_tool['name']}+Coming+Soon", use_column_width=True)
else:
with dashboard_container:
# Display the dashboard
# Header
st.markdown("""
<div style='background-color: #f0f2f6; padding: 10px; border-radius: 5px; margin-bottom: 10px;'>
<h1 style='color: #1877F2; text-align: center;'>📱 Facebook AI Writer</h1>
<p style='text-align: center;'>Generate professional Facebook content with ALwrity's AI-powered tools</p>
</div>
""", unsafe_allow_html=True)
# Group tools by category
categories = {}
for tool in facebook_tools:
category = tool["category"]
if category not in categories:
categories[category] = []
categories[category].append(tool)
# Display tools by category
for category, tools in categories.items():
st.markdown(f"## {category}")
# Create a 3-column layout for the tool cards
cols = st.columns(3)
# Display the tool cards
for i, tool in enumerate(tools):
# Determine which column to use
col = cols[i % 3]
with col:
# Create a card for each tool
status_badge = ""
if tool["status"] == "coming_soon":
status_badge = "<span style='background-color: #FFA500; color: white; padding: 2px 8px; border-radius: 10px; font-size: 0.8em;'>Coming Soon</span>"
elif tool["status"] == "future":
status_badge = "<span style='background-color: #808080; color: white; padding: 2px 8px; border-radius: 10px; font-size: 0.8em;'>Future</span>"
st.markdown(f"""
<div style='background-color: {tool["color"]}; padding: 20px; border-radius: 10px; margin-bottom: 20px; color: white;'>
<h2 style='color: white;'>{tool["icon"]} {tool["name"]} {status_badge}</h2>
<p>{tool["description"]}</p>
</div>
""", unsafe_allow_html=True)
# Add a button to access the tool
if st.button(f"Use {tool['name']}", key=f"btn_{tool['name']}"):
# Store the selected tool in session state
st.session_state.selected_tool = tool
st.rerun()
if __name__ == "__main__":
facebook_main_menu()

View File

@@ -0,0 +1,231 @@
"""
Facebook Post Generator Module
This module provides functionality to generate engaging Facebook posts with various features
and optimization options.
"""
import streamlit as st
from ...gpt_providers.text_generation.main_text_generation import llm_text_gen
from ...gpt_providers.image_generation.main_image_generation import generate_image
def write_fb_post():
"""Generate an engaging Facebook post with various features and optimization options."""
st.markdown("""
### 📝 Facebook Post Generator
Create engaging Facebook posts that drive engagement and reach. Customize your post with various features
and get AI-powered suggestions for optimal performance.
""")
# Create tabs for different sections
tab1, tab2, tab3 = st.tabs(["Post Content", "Media & Links", "Preview & Analytics"])
with tab1:
# Basic post information
col1, col2 = st.columns(2)
with col1:
post_goal_options = [
"Promote a product/service",
"Share valuable content",
"Increase engagement",
"Build brand awareness",
"Drive website traffic",
"Generate leads",
"Announce news/updates",
"Customize"
]
post_goal = st.selectbox(
"🎯 **What is the goal of your post?**",
post_goal_options,
index=2,
help="Select the main goal of your post."
)
if post_goal == "Customize":
post_goal = st.text_input(
"🎯 **Customize your goal:**",
placeholder="e.g., Announce an event",
help="Provide a specific goal if you selected 'Customize'."
)
target_audience = st.text_input(
"👥 **Describe your target audience:**",
placeholder="e.g., Fitness enthusiasts aged 25-35",
help="Describe the audience you are targeting with this post."
)
post_tone_options = [
"Informative",
"Humorous",
"Inspirational",
"Upbeat",
"Casual",
"Professional",
"Conversational",
"Customize"
]
post_tone = st.selectbox(
"🎨 **What tone do you want to use?**",
post_tone_options,
index=3,
help="Choose the tone you want to use for the post."
)
if post_tone == "Customize":
post_tone = st.text_input(
"🎨 **Customize your tone:**",
placeholder="e.g., Professional",
help="Provide a specific tone if you selected 'Customize'."
)
with col2:
business_type = st.text_input(
"🏢 **What is your business type?**",
placeholder="e.g., Fitness coach",
help="Provide the type of your business. This will help tailor the post content."
)
include = st.text_input(
"📷 **What elements do you want to include?**",
placeholder="e.g., Short video with a sneak peek of the challenge",
help="Specify any elements you want to include in the post."
)
avoid = st.text_input(
"❌ **What elements do you want to avoid?**",
placeholder="e.g., Long paragraphs",
help="Specify any elements you want to avoid in the post."
)
# Advanced options
with st.expander("Advanced Options"):
st.markdown("#### Post Structure")
use_hook = st.checkbox("Use attention-grabbing hook", value=True)
use_story = st.checkbox("Include storytelling elements", value=True)
use_cta = st.checkbox("Add clear call-to-action", value=True)
st.markdown("#### Engagement Features")
use_question = st.checkbox("Include engagement question", value=True)
use_emoji = st.checkbox("Use relevant emojis", value=True)
use_hashtags = st.checkbox("Add relevant hashtags", value=True)
with tab2:
# Media and link options
st.markdown("#### Media Options")
media_type = st.radio(
"Select media type:",
["None", "Image", "Video", "Carousel", "Link Preview"],
horizontal=True
)
if media_type == "Image":
col1, col2 = st.columns(2)
with col1:
image_source = st.radio(
"Image source:",
["Upload", "Generate with AI", "Use URL"],
horizontal=True
)
if image_source == "Upload":
uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
elif image_source == "Generate with AI":
image_prompt = st.text_area("Describe the image you want to generate")
if st.button("Generate Image"):
with st.spinner("Generating image..."):
# Call image generation function
pass
else:
image_url = st.text_input("Enter image URL")
with col2:
st.markdown("#### Image Settings")
image_position = st.selectbox(
"Image position:",
["Above post", "Below post"]
)
add_image_caption = st.checkbox("Add image caption", value=True)
elif media_type == "Video":
st.file_uploader("Upload a video", type=["mp4", "mov"])
st.checkbox("Add video thumbnail", value=True)
st.checkbox("Add video description", value=True)
elif media_type == "Carousel":
st.file_uploader("Upload multiple images", type=["jpg", "jpeg", "png"], accept_multiple_files=True)
st.checkbox("Add captions for each image", value=True)
elif media_type == "Link Preview":
st.text_input("Enter URL to preview")
st.checkbox("Customize link preview", value=False)
with tab3:
# Preview and analytics section
st.markdown("#### Post Preview")
# Generate post button
if st.button("🚀 Generate Facebook Post", key="generate_post"):
with st.spinner("Generating your post..."):
if not business_type or not target_audience:
st.error("🚫 Please provide the required inputs: Business Type and Target Audience.")
else:
# Generate the post content
prompt = f"""
Create a Facebook post for a {business_type} targeting {target_audience}.
Goal: {post_goal}
Tone: {post_tone}
Include: {include}
Avoid: {avoid}
Additional requirements:
- Use attention-grabbing hook: {use_hook}
- Include storytelling elements: {use_story}
- Add clear call-to-action: {use_cta}
- Include engagement question: {use_question}
- Use relevant emojis: {use_emoji}
- Add relevant hashtags: {use_hashtags}
Please write a well-structured Facebook post that:
1. Grabs attention in the first line
2. Maintains consistent tone throughout
3. Includes engaging content that aligns with the goal
4. Ends with a clear call-to-action
5. Uses appropriate formatting and emojis
6. Includes relevant hashtags if requested
"""
generated_post = llm_text_gen(prompt)
if generated_post:
# Display the generated post
st.markdown("### Generated Post")
st.markdown(generated_post)
# Display engagement predictions
st.markdown("### 📊 Engagement Predictions")
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Expected Reach", "2.5K - 5K")
with col2:
st.metric("Expected Engagement", "5-8%")
with col3:
st.metric("Best Time to Post", "2 PM - 4 PM")
# Display optimization suggestions
st.markdown("### 💡 Optimization Suggestions")
st.info("""
- Consider adding a question to increase comments
- Use more emojis to increase visibility
- Keep paragraphs shorter for better readability
- Add a poll to increase engagement
""")
# Copy button
st.button("📋 Copy to Clipboard", key="copy_post")
else:
st.error("Error: Failed to generate Facebook Post.")

View File

@@ -0,0 +1,246 @@
"""
Facebook Story Generator Module
This module provides functionality to generate engaging Facebook Stories with various features
and customization options.
"""
import streamlit as st
from ...gpt_providers.text_generation.main_text_generation import llm_text_gen
from ...gpt_providers.image_generation.main_image_generation import generate_image
def write_fb_story():
"""Generate an engaging Facebook Story with various features and customization options."""
st.markdown("""
### 📱 Facebook Story Generator
Create engaging Facebook Stories that capture attention and drive engagement. Customize your story
with various features and get AI-powered suggestions for optimal performance.
""")
# Create tabs for different sections
tab1, tab2, tab3 = st.tabs(["Story Content", "Visual Elements", "Preview & Analytics"])
with tab1:
# Basic story information
col1, col2 = st.columns(2)
with col1:
story_type_options = [
"Product showcase",
"Behind the scenes",
"User testimonial",
"Event promotion",
"Tutorial/How-to",
"Question/Poll",
"Announcement",
"Customize"
]
story_type = st.selectbox(
"🎯 **What type of story do you want to create?**",
story_type_options,
index=0,
help="Select the type of story you want to create."
)
if story_type == "Customize":
story_type = st.text_input(
"🎯 **Customize your story type:**",
placeholder="e.g., Product launch",
help="Provide a specific story type if you selected 'Customize'."
)
target_audience = st.text_input(
"👥 **Describe your target audience:**",
placeholder="e.g., Fashion enthusiasts aged 18-24",
help="Describe the audience you are targeting with this story."
)
story_tone_options = [
"Casual",
"Fun",
"Professional",
"Inspirational",
"Educational",
"Entertaining",
"Customize"
]
story_tone = st.selectbox(
"🎨 **What tone do you want to use?**",
story_tone_options,
index=0,
help="Choose the tone you want to use for the story."
)
if story_tone == "Customize":
story_tone = st.text_input(
"🎨 **Customize your tone:**",
placeholder="e.g., Playful",
help="Provide a specific tone if you selected 'Customize'."
)
with col2:
business_type = st.text_input(
"🏢 **What is your business type?**",
placeholder="e.g., Fashion brand",
help="Provide the type of your business. This will help tailor the story content."
)
include = st.text_input(
"📷 **What elements do you want to include?**",
placeholder="e.g., Product demonstration, customer testimonial",
help="Specify any elements you want to include in the story."
)
avoid = st.text_input(
"❌ **What elements do you want to avoid?**",
placeholder="e.g., Long text overlays",
help="Specify any elements you want to avoid in the story."
)
# Advanced options
with st.expander("Advanced Options"):
st.markdown("#### Story Structure")
use_hook = st.checkbox("Use attention-grabbing opening", value=True)
use_story = st.checkbox("Include storytelling elements", value=True)
use_cta = st.checkbox("Add clear call-to-action", value=True)
st.markdown("#### Engagement Features")
use_question = st.checkbox("Include engagement question", value=True)
use_emoji = st.checkbox("Use relevant emojis", value=True)
use_hashtags = st.checkbox("Add relevant hashtags", value=True)
use_stickers = st.checkbox("Add interactive stickers", value=True)
with tab2:
# Visual elements options
st.markdown("#### Visual Elements")
# Background options
st.markdown("##### Background")
background_type = st.radio(
"Select background type:",
["Solid color", "Gradient", "Image", "Video"],
horizontal=True
)
if background_type == "Solid color":
st.color_picker("Choose background color", "#FFFFFF")
elif background_type == "Gradient":
col1, col2 = st.columns(2)
with col1:
st.color_picker("Start color", "#FFFFFF")
with col2:
st.color_picker("End color", "#000000")
elif background_type == "Image":
image_source = st.radio(
"Image source:",
["Upload", "Generate with AI", "Use URL"],
horizontal=True
)
if image_source == "Upload":
st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
elif image_source == "Generate with AI":
image_prompt = st.text_area("Describe the image you want to generate")
if st.button("Generate Image"):
with st.spinner("Generating image..."):
# Call image generation function
pass
else:
st.text_input("Enter image URL")
else:
st.file_uploader("Upload a video", type=["mp4", "mov"])
# Text overlay options
st.markdown("##### Text Overlay")
text_style = st.selectbox(
"Text style:",
["Minimal", "Bold", "Playful", "Professional", "Custom"]
)
if text_style == "Custom":
st.text_input("Custom text style description")
text_color = st.color_picker("Text color", "#000000")
text_position = st.selectbox(
"Text position:",
["Top", "Middle", "Bottom", "Custom"]
)
# Interactive elements
st.markdown("##### Interactive Elements")
use_poll = st.checkbox("Add poll", value=False)
use_quiz = st.checkbox("Add quiz", value=False)
use_slider = st.checkbox("Add slider", value=False)
use_countdown = st.checkbox("Add countdown", value=False)
with tab3:
# Preview and analytics section
st.markdown("#### Story Preview")
# Generate story button
if st.button("🚀 Generate Facebook Story", key="generate_story"):
with st.spinner("Generating your story..."):
if not business_type or not target_audience:
st.error("🚫 Please provide the required inputs: Business Type and Target Audience.")
else:
# Generate the story content
prompt = f"""
Create a Facebook Story for a {business_type} targeting {target_audience}.
Story Type: {story_type}
Tone: {story_tone}
Include: {include}
Avoid: {avoid}
Additional requirements:
- Use attention-grabbing opening: {use_hook}
- Include storytelling elements: {use_story}
- Add clear call-to-action: {use_cta}
- Include engagement question: {use_question}
- Use relevant emojis: {use_emoji}
- Add relevant hashtags: {use_hashtags}
- Add interactive stickers: {use_stickers}
Please write a well-structured Facebook Story that:
1. Grabs attention in the first frame
2. Maintains consistent tone throughout
3. Includes engaging content that aligns with the story type
4. Ends with a clear call-to-action
5. Uses appropriate formatting and emojis
6. Includes relevant hashtags if requested
7. Incorporates interactive elements if selected
"""
generated_story = llm_text_gen(prompt)
if generated_story:
# Display the generated story
st.markdown("### Generated Story")
st.markdown(generated_story)
# Display engagement predictions
st.markdown("### 📊 Engagement Predictions")
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Expected Views", "1K - 2K")
with col2:
st.metric("Expected Engagement", "8-12%")
with col3:
st.metric("Best Time to Post", "6 PM - 8 PM")
# Display optimization suggestions
st.markdown("### 💡 Optimization Suggestions")
st.info("""
- Add more interactive elements to increase engagement
- Keep text overlays short and readable
- Use vibrant colors to stand out
- Add music to increase watch time
""")
# Copy button
st.button("📋 Copy to Clipboard", key="copy_story")
else:
st.error("Error: Failed to generate Facebook Story.")

View File

@@ -1,119 +0,0 @@
import time
import os
import json
import requests
import streamlit as st
#from streamlit_quill import st_quill
from ..gpt_providers.text_generation.main_text_generation import llm_text_gen
def generate_facebook_post(business_type, target_audience, post_goal, post_tone, include, avoid):
"""
Generates a Facebook post prompt for an LLM based on user input.
"""
prompt = f"""
I am a {business_type} looking to engage my target audience, {target_audience}, on Facebook.
My goal for this detailed post is: {post_goal}. The tone should be {post_tone}.
Here are some additional preferences:
- **Include:** {include}
- **Avoid:** {avoid}
Please write a well-structured Facebook post with:
1. A **catchy opening** to grab attention.
2. Detailed **Engaging content** that highlights key benefits or features.
3. A **strong call-to-action** (CTA) encouraging my audience to take action.
4. If applicable, suggest **multimedia** (images, videos, etc.).
5. Include **relevant hashtags** for visibility.
"""
try:
response = llm_text_gen(prompt)
return response
except Exception as err:
st.error(f"An error occurred while generating the prompt: {err}")
return None
def facebook_post_writer():
st.title("📱 Alwrity - Facebook Post Generator")
st.markdown(
"""
Facebook Post Generator will help you create a compelling Facebook post for your business.
Please provide the following details to generate your post:
"""
)
# Inputs for the Facebook post generator
col1, col2 = st.columns(2)
with col1:
post_goal_options = ["Promote a new product", "Share valuable content", "Increase engagement", "Customize"]
post_goal = st.selectbox(
"🎯 **What is the goal of your post?**",
post_goal_options,
index=2,
help="Select the main goal of your post."
)
if post_goal == "Customize":
post_goal = st.text_input(
"🎯 **Customize your goal:**",
placeholder="e.g., Announce an event",
help="Provide a specific goal if you selected 'Customize'."
)
target_audience = st.text_input(
"👥 **Describe your target audience:**",
placeholder="e.g., Fitness enthusiasts",
help="Describe the audience you are targeting with this post."
)
include = st.text_input(
"📷 **What elements do you want to include?**",
placeholder="e.g., Short video with a sneak peek of the challenge",
help="Specify any elements you want to include in the post (e.g., images, videos, links, hashtags, questions)."
)
with col2:
post_tone_options = ["Informative", "Humorous", "Inspirational", "Upbeat", "Casual", "Customize"]
post_tone = st.selectbox(
"🎨 **What tone do you want to use?**",
post_tone_options,
index=3,
help="Choose the tone you want to use for the post."
)
if post_tone == "Customize":
post_tone = st.text_input(
"🎨 **Customize your tone:**",
placeholder="e.g., Professional",
help="Provide a specific tone if you selected 'Customize'."
)
business_type = st.text_input(
"🏢 **What is your business type?**",
placeholder="e.g., Fitness coach",
help="Provide the type of your business. This will help tailor the post content."
)
avoid = st.text_input(
"❌ **What elements do you want to avoid?**",
placeholder="e.g., Long paragraphs",
help="Specify any elements you want to avoid in the post (e.g., long paragraphs, technical jargon)."
)
# Handle the generation button
if st.button("🚀 Generate Facebook Post"):
with st.spinner():
if not business_type or not target_audience:
st.error("🚫 Please provide the required inputs: Business Type and Target Audience.")
else:
generated_post = generate_facebook_post(
business_type, target_audience, post_goal, post_tone, include, avoid
)
if generated_post:
st.markdown(generated_post)
else:
st.error("Error: Failed to generate Facebook Post.")

View File

@@ -3,7 +3,9 @@ import os
import sys
from pathlib import Path
import google.generativeai as genai
from google import genai
from google.genai import types
from dotenv import load_dotenv
load_dotenv(Path('../../../.env'))
from loguru import logger
@@ -30,7 +32,7 @@ def gemini_text_response(prompt, temperature, top_p, n, max_tokens, system_promp
""" Common functiont to get response from gemini pro Text. """
#FIXME: Include : https://github.com/google-gemini/cookbook/blob/main/quickstarts/rest/System_instructions_REST.ipynb
try:
genai.configure(api_key=os.getenv('GEMINI_API_KEY'))
client = genai.Client(api_key=os.getenv('GEMINI_API_KEY'))
except Exception as err:
logger.error(f"Failed to configure Gemini: {err}")
logger.info(f"Temp: {temperature}, MaxTokens: {max_tokens}, TopP: {top_p}, N: {n}")
@@ -42,19 +44,20 @@ def gemini_text_response(prompt, temperature, top_p, n, max_tokens, system_promp
"max_output_tokens": max_tokens,
}
# FIXME: Expose model_name in main_config
model = genai.GenerativeModel(model_name="gemini-1.5-pro-latest",
generation_config=generation_config,
system_instruction=system_prompt)
try:
# text_response = []
response = model.generate_content(prompt, stream=True)
if response:
for chunk in response:
# text_response.append(chunk.text)
print(chunk.text)
else:
print(response)
logger.info(f"Number of Token in Prompt Sent: {model.count_tokens(prompt)}")
response = client.models.generate_content(
model='gemini-2.0-flash-001',
contents=prompt,
config=types.GenerateContentConfig(
system_instruction=system_prompt,
max_output_tokens=max_tokens,
temperature=temperature,
top_p=top_p,
top_k=n,
),
)
#logger.info(f"Number of Token in Prompt Sent: {model.count_tokens(prompt)}")
return response.text
except Exception as err:
logger.error(f"Failed to get response from Gemini: {err}. Retrying.")

View File

@@ -9,7 +9,7 @@ from lib.ai_writers.long_form_ai_writer import long_form_generator
from lib.ai_writers.ai_news_article_writer import ai_news_generation
#from lib.ai_writers.ai_agents_crew_writer import ai_agents_writers
from lib.ai_writers.ai_financial_writer import write_basic_ta_report
from lib.ai_writers.facebook_ai_writer import facebook_post_writer
from lib.ai_writers.ai_facebook_writer.facebook_ai_writer import facebook_post_writer
from lib.ai_writers.linkedin_ai_writer import linked_post_writer
from lib.ai_writers.twitter_ai_writer import tweet_writer
from lib.ai_writers.insta_ai_writer import insta_writer

View File

@@ -6,7 +6,7 @@ from lib.utils.alwrity_utils import ai_social_writer
from lib.utils.seo_tools import ai_seo_tools
from lib.utils.settings_page import render_settings_page
# Import social media writer functions
from lib.ai_writers.facebook_ai_writer import facebook_post_writer
from lib.ai_writers.ai_facebook_writer.facebook_ai_writer import facebook_post_writer
from lib.ai_writers.linkedin_ai_writer import linked_post_writer
from lib.ai_writers.twitter_ai_writer import tweet_writer
from lib.ai_writers.insta_ai_writer import insta_writer

View File

@@ -6,7 +6,7 @@ beautifulsoup4==4.12.2
aiohttp>=3.11.11
openai>=1.3.7
PyPDF2>=3.0.1
google-genai>=1.0.0
google-genai>=1.9.0
anthropic>=0.18.1
tenacity>=8.2.3
tabulate>=0.9.0