Skip to content

Commit a9a19f1

Browse files
committed
Try Competitor Analysis
1 parent d2bb42c commit a9a19f1

File tree

4 files changed

+288
-275
lines changed

4 files changed

+288
-275
lines changed

alwrity.py

+7-270
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,11 @@
1616
import requests
1717
from rich import print
1818
from rich.text import Text
19-
2019
load_dotenv(Path('.env'))
2120

2221
app = typer.Typer()
2322

24-
from lib.ai_web_researcher.gpt_online_researcher import gpt_web_researcher
25-
from lib.ai_web_researcher.metaphor_basic_neural_web_search import metaphor_find_similar
26-
from lib.ai_writers.keywords_to_blog import write_blog_from_keywords
27-
from lib.ai_writers.speech_to_blog.main_audio_to_blog import generate_audio_blog
28-
from lib.gpt_providers.text_generation.ai_story_writer import ai_story_generator
29-
from lib.gpt_providers.text_generation.ai_essay_writer import ai_essay_generator
23+
from lib.utils.alwrity_utils import blog_from_audio, blog_from_keyword, do_web_research, do_web_research, write_story, essay_writer, blog_tools, competitor_analysis
3024

3125

3226
def prompt_for_time_range():
@@ -67,10 +61,10 @@ def start_interactive_mode():
6761
("AI Blog Writer", "AI Blog Writer"),
6862
("AI Story Writer", "AI Story Writer"),
6963
("AI Essay Writer", "AI Essay Writer"),
64+
("Online Blog Tools/Apps", "Online Blog Tools/Apps"),
7065
("Do keyword Research", "Do keyword Research"),
71-
("Create Blog Images(TBD)", "Create Blog Images(TBD)"),
7266
("Competitor Analysis", "Competitor Analysis"),
73-
("Online Blog Tools/Apps", "Online Blog Tools/Apps"),
67+
("Create Blog Images(TBD)", "Create Blog Images(TBD)"),
7468
("AI Social Media(TBD)", "AI Social Media(TBD)"),
7569
("Quit", "Quit")
7670
]
@@ -154,188 +148,6 @@ def get_api_key(api_key: str, api_description: str):
154148
print(f"✅ {api_description} API Key added to .env file.")
155149

156150

157-
# FIXME
158-
def faq_generator():
159-
return
160-
161-
162-
def write_story():
163-
""" Alwrity AI Story Writer """
164-
personas = [
165-
("Award-Winning Science Fiction Author", "Award-Winning Science Fiction Author"),
166-
("Historical Fiction Author", "Historical Fiction Author"),
167-
("Fantasy World Builder", "Fantasy World Builder"),
168-
("Mystery Novelist", "Mystery Novelist"),
169-
("Romantic Poet", "Romantic Poet"),
170-
("Thriller Writer", "Thriller Writer"),
171-
("Children's Book Author", "Children's Book Autho"),
172-
("Satirical Humorist", "Satirical Humorist"),
173-
("Biographical Writer", "Biographical Writer"),
174-
("Dystopian Visionary", "Dystopian Visionary"),
175-
("Magical Realism Author", "Magical Realism Author")
176-
]
177-
178-
dialog = radiolist_dialog(
179-
title="Select Your Story Writing Persona Or Book Genre",
180-
text="Choose a persona that resonates you want AI Story Writer to adopt.",
181-
values=personas
182-
)
183-
184-
selected_persona_name = dialog.run()
185-
# Define persona descriptions
186-
persona_descriptions = {
187-
"Award-Winning Science Fiction Author": "You are an award-winning science fiction author with a penchant for expansive, intricately woven stories. Your ultimate goal is to write the next award-winning sci-fi novel.",
188-
"Historical Fiction Author": "You are a seasoned historical fiction author, meticulously researching past eras to weave captivating narratives. Your goal is to transport readers to different times and places through your vivid storytelling.",
189-
"Fantasy World Builder": "You are a world-building enthusiast, crafting intricate realms filled with magic, mythical creatures, and epic quests. Your ambition is to create the next immersive fantasy saga that captivates readers' imaginations.",
190-
"Mystery Novelist": "You are a master of suspense and intrigue, intricately plotting out mysteries with unexpected twists and turns. Your aim is to keep readers on the edge of their seats, eagerly turning pages to unravel the truth.",
191-
"Romantic Poet": "You are a romantic at heart, composing verses that capture the essence of love, longing, and human connections. Your dream is to write the next timeless love story that leaves readers swooning.",
192-
"Thriller Writer": "You are a thrill-seeker, crafting adrenaline-pumping tales of danger, suspense, and high-stakes action. Your mission is to keep readers hooked from start to finish with heart-pounding thrills and unexpected twists.",
193-
"Children's Book Author": "You are a storyteller for the young and young at heart, creating whimsical worlds and lovable characters that inspire imagination and wonder. Your goal is to spark joy and curiosity in young readers with enchanting tales.",
194-
"Satirical Humorist": "You are a keen observer of society, using humor and wit to satirize the absurdities of everyday life. Your aim is to entertain and provoke thought, delivering biting social commentary through clever and humorous storytelling.",
195-
"Biographical Writer": "You are a chronicler of lives, delving into the stories of real people and events to illuminate the human experience. Your passion is to bring history to life through richly detailed biographies that resonate with readers.",
196-
"Dystopian Visionary": "You are a visionary writer, exploring dark and dystopian futures that reflect contemporary fears and anxieties. Your vision is to challenge societal norms and provoke reflection on the path humanity is heading.",
197-
"Magical Realism Author": "You are a purveyor of magical realism, blending the ordinary with the extraordinary to create enchanting and thought-provoking tales. Your goal is to blur the lines between reality and fantasy, leaving readers enchanted and introspective."
198-
}
199-
if selected_persona_name:
200-
selected_persona = next((persona for persona in personas if persona[0] == selected_persona_name), None)
201-
if selected_persona:
202-
character_input = input_dialog(
203-
title=f"Enter characters for {selected_persona[0]}",
204-
text=persona_descriptions[selected_persona_name]
205-
).run()
206-
207-
#FIXME/TBD: Presently supports gemini only. Openai, minstral coming up.
208-
# Check if LLM API KEYS are present and Not none.
209-
if os.getenv('GEMINI_API_KEY'):
210-
ai_story_generator(selected_persona_name, selected_persona_name, character_input)
211-
else:
212-
print(f"ERROR: Provide Google Gemini API keys. Openai, mistral, ollama coming up.")
213-
exit(1)
214-
215-
216-
217-
def essay_writer():
218-
# Define essay types and education levels
219-
essay_types = [
220-
("Argumentative", "Argumentative - Forming an opinion via research. Building an evidence-based argument."),
221-
("Expository", "Expository - Knowledge of a topic. Communicating information clearly."),
222-
("Narrative", "Narrative - Creative language use. Presenting a compelling narrative."),
223-
("Descriptive", "Descriptive - Creative language use. Describing sensory details.")
224-
]
225-
226-
education_levels = [
227-
("Primary School", "Primary School"),
228-
("High School", "High School"),
229-
("College", "College"),
230-
("Graduate School", "Graduate School")
231-
]
232-
233-
# Define the options for number of pages
234-
num_pages_options = [
235-
("Short Form (1-2 pages)", "Short Form"),
236-
("Medium Form (3-5 pages)", "Medium Form"),
237-
("Long Form (6+ pages)", "Long Form")
238-
]
239-
240-
# Ask the user for the title of the essay
241-
essay_title = input_dialog(title="Essay Title", text="Enter the title of your essay:").run()
242-
while not essay_title.strip():
243-
print("Please enter a valid title for your essay.")
244-
essay_title = input_dialog(title="Essay Title", text="Enter the title of your essay:").run()
245-
246-
# Ask the user for type of essay, level of education, and number of pages
247-
selected_essay_type = radiolist_dialog(title="Type of Essay", text="Choose the type of essay you want to write:",
248-
values=essay_types).run()
249-
250-
selected_education_level = radiolist_dialog(title="Level of Education", text="Choose your level of education:",
251-
values=education_levels).run()
252-
253-
# Prompt the user to select the length of the essay
254-
num_pages_prompt = "Select the length of your essay:"
255-
selected_num_pages = radiolist_dialog(title="Number of Pages", text=num_pages_prompt, values=num_pages_options).run()
256-
257-
ai_essay_generator(essay_title, selected_essay_type, selected_education_level, selected_num_pages)
258-
259-
260-
261-
def blog_tools():
262-
os.system("clear" if os.name == "posix" else "cls")
263-
text = "_______________________________________________________________________\n"
264-
text += "\n⚠️ Alert! 💥❓💥\n"
265-
text += "Collection of Helpful Blogging Tools, powered by LLMs.\n"
266-
text += "_______________________________________________________________________\n"
267-
print(text)
268-
269-
personas = [
270-
("Write Blog Title", "Write Blog Title"),
271-
("Write Blog Meta Description", "Write Blog Meta Description"),
272-
# ("Write Blog Introduction", "Write Blog Introduction"),
273-
# ("Write Blog conclusion", "Write Blog conclusion"),
274-
# ("Write Blog Outline", "Write Blog Outline"),
275-
("Generate Blog FAQs", "Generate Blog FAQs"),
276-
("AI Linkedin Post", "AI Linkedin Post"),
277-
# ("Research blog references", "Research blog references"),
278-
# ("Convert Blog To HTML", "Convert Blog To HTML"),
279-
# ("Convert Blog To Markdown", "Convert Blog To Markdown"),
280-
# ("Blog Proof Reader", "Blog Proof Reader"),
281-
# ("Get Blog Tags", "Get Blog Tags"),
282-
# ("Get blog categories", "Get blog categories"),
283-
# ("Get Blog Code Examples", "Get Blog Code Examples"),
284-
# ("Check WebPage Performance", "Check WebPage Performance"),
285-
("Quit/Exit", "Quit/Exit")
286-
]
287-
dialog = radiolist_dialog(
288-
title = "Select Your AI content tool.",
289-
text = "Choose a tool to use and visit provided online link to try them out.",
290-
values = personas
291-
)
292-
293-
selected_persona_name = dialog.run()
294-
295-
persona_descriptions = {
296-
"Write Blog Title": "Write Blog Title - VISIT: https://alwrity-title.streamlit.app/",
297-
"Write Blog Meta Description": "Write Blog Meta Description - VISIT: https://alwrity-metadesc.streamlit.app/",
298-
# "Write Blog Introduction": "Write Blog Introduction - To Be Done (TBD)",
299-
# "Write Blog conclusion": "Write Blog conclusion - ",
300-
# "Write Blog Outline": "Write Blog Outline - ",
301-
"Generate Blog FAQs": "Generate Blog FAQs - VISIT: https://alwrity-faq.streamlit.app/",
302-
"AI Linkedin Post": "AI Linkedin Post writer - VISIT: https://alwrity-linkedin.streamlit.app/",
303-
# "Research blog references": "Research blog references - Example: https://example.com/research-blog-references",
304-
# "Convert Blog To HTML": "Convert Blog To HTML - Example: https://example.com/convert-blog-to-html",
305-
# "Convert Blog To Markdown": "Convert Blog To Markdown - Example: https://example.com/convert-blog-to-markdown",
306-
# "Blog Proof Reader": "Blog Proof Reader - Example: https://example.com/blog-proof-reader",
307-
# "Get Blog Tags": "Get Blog Tags - Example: https://example.com/get-blog-tags",
308-
# "Get blog categories": "Get blog categories - Example: https://example.com/get-blog-categories",
309-
# "Get Blog Code Examples": "Get Blog Code Examples - Example: https://example.com/get-blog-code-examples",
310-
# "SEO Checks": "SEO checks - TBD",
311-
"Quit/Exit": "Quit/Exit - Example: Quit/Exit"
312-
}
313-
314-
if selected_persona_name:
315-
selected_persona = next((persona for persona in personas if persona[0] == selected_persona_name), None)
316-
if selected_persona:
317-
character_input = message_dialog(
318-
title=f"To Try {selected_persona_name}, Visit below URL:",
319-
text=persona_descriptions[selected_persona_name]
320-
).run()
321-
322-
323-
324-
def competitor_analysis():
325-
text = "_______________________________________________________________________\n"
326-
text += "\n⚠️ Alert! 💥❓💥\n"
327-
text += "Provide competitor's URL, get details of similar/alternative companies.\n"
328-
text += "Usecases: Know similar companies and alternatives, to given URL\n"
329-
text += "_______________________________________________________________________\n"
330-
print(text)
331-
similar_url = prompt("Enter Valid URL to get web analysis")
332-
try:
333-
metaphor_find_similar(similar_url)
334-
except Exception as err:
335-
print(f"[bold red]✖ 🚫 Failed to do similar search.\nError:{err}[/bold red]")
336-
return
337-
338-
339151
def write_blog():
340152
blog_type = write_blog_options()
341153
if blog_type:
@@ -356,86 +168,10 @@ def write_blog():
356168
raise typer.Exit()
357169

358170

359-
def blog_from_audio():
360-
"""
361-
Prompt the user to input either a YouTube URL, a file location, or keywords to search on YouTube.
362-
Validate the input and take appropriate actions based on the input type.
363-
"""
364-
365-
while True:
366-
print("https://github.com/AJaySi/AI-Blog-Writer/wiki/Audio-to-blog-AI-article-writer-%E2%80%90-Alwrity-Speech-To-Text-Feature")
367-
audio_input = prompt("""Enter Youtube video URL OR provide Full-Path to audio file.\n👋 : """)
368-
# If the user cancels, exit the loop and the application
369-
if audio_input is None:
370-
break
371-
372-
# If the user presses OK without providing any input, prompt again
373-
if not audio_input.strip():
374-
continue
375-
376-
# Check if the input is a valid YouTube URL
377-
if audio_input.startswith("https://www.youtube.com/") or audio_input.startswith("http://www.youtube.com/") or os.path.exists(audio_input):
378-
# Validate YouTube URL, Process YouTube URL
379-
generate_audio_blog(audio_input)
380-
break
381-
382-
383-
def blog_from_keyword():
384-
""" Input blog keywords, research and write a factual blog."""
385-
while True:
386-
print("________________________________________________________________")
387-
blog_keywords = input_dialog(
388-
title='Enter Keywords/Blog Title',
389-
text='Shit in, Shit Out; Better keywords, better research, hence better content.\n👋 Enter keywords/Blog Title for blog generation:',
390-
).run()
391-
392-
# If the user cancels, exit the loop
393-
if blog_keywords is None:
394-
break
395-
if blog_keywords and len(blog_keywords.split()) >= 2:
396-
break
397-
else:
398-
message_dialog(
399-
title='Error',
400-
text='🚫 Blog keywords should be at least two words long. Please try again.'
401-
).run()
402-
if blog_keywords:
403-
try:
404-
write_blog_from_keywords(blog_keywords)
405-
except Exception as err:
406-
print(f"Failed to write blog on {blog_keywords}, Error: {err}\n")
407-
exit(1)
408-
409-
410-
def do_web_research():
411-
""" Input keywords and do web research and present a report."""
412-
if check_search_apis():
413-
while True:
414-
print("________________________________________________________________")
415-
search_keywords = input_dialog(
416-
title='Enter Search Keywords below: More Options in main_config.',
417-
text='👋 Enter keywords for web research (Or keywords from your blog):',
418-
).run()
419-
if search_keywords and len(search_keywords.split()) >= 2:
420-
break
421-
else:
422-
message_dialog(
423-
title='Warning',
424-
text='🚫 Search keywords should be at least three words long. Please try again.'
425-
).run()
426-
427-
try:
428-
print(f"🚀🎬🚀 [bold green]Starting web research on given keywords: {search_keywords}..")
429-
web_research_result = gpt_web_researcher(search_keywords)
430-
except Exception as err:
431-
print(f"\n💥🤯 [bold red]ERROR 🤯 : Failed to do web research: {err}\n")
432-
433-
434-
435171
def check_llm_environs():
436172
""" Function to check which LLM api is given. """
437173
# Load .env file
438-
load_dotenv()
174+
load_dotenv(Path('.env'))
439175
# Check if GPT_PROVIDER is defined in .env file
440176
gpt_provider = os.getenv("GPT_PROVIDER")
441177

@@ -454,8 +190,9 @@ def check_llm_environs():
454190
]
455191
).run()
456192
gpt_provider = selected_provider
193+
# Update .env file
457194
os.environ["GPT_PROVIDER"] = gpt_provider
458-
195+
459196
if gpt_provider == "Google":
460197
api_key_var = "GEMINI_API_KEY"
461198
missing_api_msg = f"To get your {api_key_var}, please visit: https://aistudio.google.com/app/apikey"
@@ -473,8 +210,8 @@ def check_llm_environs():
473210

474211
# Update .env file
475212
with open(".env", "a", encoding="utf-8") as env_file:
476-
env_file.write(f"GPT_PROVIDER={gpt_provider}\n")
477213
env_file.write(f"{api_key_var}={api_key}\n")
214+
env_file.write(f"GPT_PROVIDER={gpt_provider}\n")
478215

479216

480217

lib/ai_web_researcher/gpt_competitor_analysis.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from ..gpt_providers.text_generation.main_text_generation import llm_text_gen
1111

1212

13-
def summarize_competitor_content(research_content, gpt_providers="openai"):
13+
def summarize_competitor_content(research_content):
1414
"""Combine the given online research and gpt blog content"""
1515

1616
prompt = f"""You are a helpful assistant writing a research report about a company. I will provide you with company details.
@@ -23,7 +23,7 @@ def summarize_competitor_content(research_content, gpt_providers="openai"):
2323
Company details: '{research_content}'"""
2424

2525
try:
26-
response = gemini_text_response(prompt)
26+
response = llm_text_gen(prompt)
2727
return response
2828
except Exception as err:
2929
logger.error(f"Failed to get response from LLM: {err}")

lib/ai_web_researcher/metaphor_basic_neural_web_search.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def metaphor_find_similar(similar_url):
8080
search_response = metaphor.search_and_contents(
8181
acompetitor.url,
8282
type="keyword",
83-
num_results=5
83+
num_results=3
8484
)
8585
except Exception as err:
8686
logger.error(f"Failed to do metaphor keyword/url research: {err}")
@@ -90,11 +90,10 @@ def metaphor_find_similar(similar_url):
9090
for r in tqdm(research_response, desc=f"{acompetitor.url}", unit="research"):
9191
all_contents += r.text
9292
try:
93-
acompetitor.text = summarize_competitor_content(all_contents, "gemini")
93+
acompetitor.text = summarize_competitor_content(all_contents)
9494
except Exception as err:
9595
logger.error(f"Failed to summarize_web_content: {err}")
9696

97-
print(competitors)
9897
print_search_result(competitors)
9998
return search_response
10099

0 commit comments

Comments
 (0)