SynthAI-Company-Refresher / company_website.py
Adr740's picture
Update company_website.py
ac4cc69 verified
import os
import json
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
from nltk.tokenize import sent_tokenize
from openai import OpenAI
from groq import Groq
import tiktoken
from linkedin import get_linkedin_profile
from config import openai_api, groq_api, models
import google.generativeai as genai
from config import gemini_api
client = ""
enc = tiktoken.get_encoding("cl100k_base")
def get_website_link(name, folder_path="data_dumpster"):
file_name = f"linkedin_content.json"
# folder_path = os.path.join(folder_path, file_name)
if not os.path.isfile(folder_path):
linkedin_content = get_linkedin_profile(name=name, folder_path=folder_path)
url = linkedin_content['profile']['website']
else:
with open(folder_path, "r") as file:
url = json.load(file)['profile']['website']
return url
def get_readable_content(url):
def fetch_content(url):
try:
response = requests.get(url)
response.raise_for_status()
except requests.RequestException as e:
print(f"Error fetching {url}: {e}")
return None
soup = BeautifulSoup(response.content, 'html.parser')
for tag in soup(['script','style']):
tag.decompose()
text = soup.get_text()
lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
content = '\n'.join(chunk for chunk in chunks if chunk)
sentences = sent_tokenize(content)
content =''.join(sentences)
return {'url': url, 'content': content}
return fetch_content(url)
def save_website_content(url, folder_path="data_dumpster"):
content = get_readable_content(url)
with open(f"{folder_path}/{url.replace('/','_SLASH_')}.txt", "w") as fil:
if content:
fil.write(content["content"])
else:
fil.write("Could not access website")
return content
def curate_relevant_links(list_links, llm_provider="openai"):
#neo prompt "content": "You will be given a list of links and their description formatted as a list of tuples. Your task is to output MAXIMUM 30 urls from this list that are most relevant ones to consult to find information on the company following items (cover them all!):\n\n- company summary\n- offering and products\n- customer segment\n- HQ and offices locations\n- financials and activity\n- ownership structure\n- news/press\n- history (funding/acquisitions etc.)\n- stage in the value chain, end customers, market segment/customers, business model\n\nYour output format is a dict with as first field \"explanation\" explaining your reasoning and then a field \"urls\" with the list of the urls to consult with the highest likelihood of containing info on the items under investigation. Your output will be directly fed into a python code so do not write anything except this json."
try:
response = client.chat.completions.create(
model= models[llm_provider],
stream=False,
response_format={"type": "json_object"},
messages=[
{
"role": "system",
"content": """
You will be given a list of links and their description formatted as a list of tuples.
Your task is to go through this list, select and output only the 30 of them (if the length of the list is bigger than 30) that are the most relevant ones to consult. Don't invent new links, rely 100\% to the given list.
Rank them by likelihood to contain information on the company following items (cover them all!):
- company summary
- offering and products
- customer segment
- HQ and offices locations
- financials and activity
- ownership structure
- news/press
- history (funding/acquisitions etc.)
- stage in the value chain, end customers, market segment/customers, business model
Your output format is a dict with as first field \"explanation\" explaining your reasoning and then a field \"urls\" with the list of the urls to consult with the highest likelihood of containing info on the items under investigation. Your output will be directly fed into a python code so do not write anything except this json.
"""
},
{
"role": "user",
"content": str(list_links)
}
],
temperature=0,
max_tokens=2000,
top_p=1,
frequency_penalty=0,
presence_penalty=0
).choices[0].message.content
except:
print("Too long for groq, trying now openai")
print("Original provider: ", llm_provider)
client = OpenAI(api_key=openai_api)
response = client.chat.completions.create(
model= 'gpt-4o',
stream=False,
response_format={"type": "json_object"},
messages=[
{
"role": "system",
"content": "You will be given a list of links and their description formatted as a list of tuples. Your task is to output only the 30 (if there are more than 30) most relevant ones to consult ranked by likelihood to contain information on the company following items (cover them all!):\n\n- company summary\n- offering and products\n- customer segment\n- HQ and offices locations\n- financials and activity\n- ownership structure\n- news/press\n- history (funding/acquisitions etc.)\n- stage in the value chain, end customers, market segment/customers, business model\n\nYour output format is a dict with as first field \"explanation\" explaining your reasoning and then a field \"urls\" with the list of the urls to consult with the highest likelihood of containing info on the items under investigation. Your output will be directly fed into a python code so do not write anything except this json."
},
{
"role": "user",
"content": str(list_links)
}
],
temperature=1,
max_tokens=1558,
top_p=1,
frequency_penalty=0,
presence_penalty=0
).choices[0].message.content
return response
def curate_relevant_links_gemini(list_links):
#neo prompt "content": "You will be given a list of links and their description formatted as a list of tuples. Your task is to output MAXIMUM 30 urls from this list that are most relevant ones to consult to find information on the company following items (cover them all!):\n\n- company summary\n- offering and products\n- customer segment\n- HQ and offices locations\n- financials and activity\n- ownership structure\n- news/press\n- history (funding/acquisitions etc.)\n- stage in the value chain, end customers, market segment/customers, business model\n\nYour output format is a dict with as first field \"explanation\" explaining your reasoning and then a field \"urls\" with the list of the urls to consult with the highest likelihood of containing info on the items under investigation. Your output will be directly fed into a python code so do not write anything except this json."
genai.configure(api_key=gemini_api)
# Create the model
# See https://ai.google.dev/api/python/google/generativeai/GenerativeModel
generation_config = {
"temperature": 1,
"top_p": 0.95,
"top_k": 64,
"max_output_tokens": 8192,
"response_mime_type": "application/json",
}
safety_settings = [
{
"category": "HARM_CATEGORY_HARASSMENT",
"threshold": "BLOCK_MEDIUM_AND_ABOVE",
},
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"threshold": "BLOCK_MEDIUM_AND_ABOVE",
},
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"threshold": "BLOCK_MEDIUM_AND_ABOVE",
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"threshold": "BLOCK_MEDIUM_AND_ABOVE",
},
]
enc = tiktoken.get_encoding("cl100k_base")
links_txt = str(list_links)
toks = enc.encode(links_txt)
if len(toks) >= 900000:
chunk_size = int(len(links_txt) // (len(toks) / 900000))
chunk_size
links_txt = links_txt[:chunk_size]
model = genai.GenerativeModel(
model_name="gemini-1.5-flash-latest",
safety_settings=safety_settings,
generation_config=generation_config,
system_instruction= "You will be given a list of links and their description formatted as a list of tuples. \nYour task is to go through this list, select and output only the 30 of them (if the length of the list is bigger than 30) that are the most relevant ones to consult. Don't invent new links, rely 100\% to the given list.\nRank them by likelihood to contain information on the company following items (cover them all!):\n\n- company summary\n- offering and products\n- customer segment\n- HQ and offices locations\n- financials and activity\n- ownership structure\n- news/press\n- history (funding/acquisitions etc.)\n- stage in the value chain, end customers, market segment/customers, business model\n\nYour output format is a dict with as first field \"explanation\" explaining your reasoning and then a field \"urls\" with the list of the urls to consult with the highest likelihood of containing info on the items under investigation. Your output will be directly fed into a python code so do not write anything except this json."
)
chat_session = model.start_chat(
history=[],
)
response = chat_session.send_message(f"{links_txt}")
return response.text
def get_all_relevant_links(url, llm_provider="groq"):
print(f"Going through all the pages of {url}, this might take a minute or two")
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
base_url = url
links_with_text = []
for a in soup.find_all('a', href=True):
link_url = a.get('href')
link_text = a.text.strip()
parent_tag = a.parent
if not link_url.startswith('http'):
link_url = urljoin(base_url, link_url)
links_with_text.append((link_url, link_text))
links_with_text = list(set(links_with_text))
print("Number of links to visit found: ", len(links_with_text))
if len(links_with_text) > 30:
print("That's a lot... finding the most relevant ones...")
links_to_explore = eval(curate_relevant_links(str(links_with_text), llm_provider=llm_provider))
# links_to_explore = eval(curate_relevant_links_gemini(str(links_with_text)))
else:
links_to_explore = {"explanation" : "All links will be visited", "urls": [t[0] for t in links_with_text]}
return links_to_explore
def download_pdf(url, save_path):
response = requests.get(url)
if response.status_code == 200:
os.makedirs(os.path.dirname(save_path), exist_ok=True)
with open(save_path, 'wb') as file:
file.write(response.content)
print("PDF downloaded successfully!")
else:
print("Failed to download PDF")
def full_company_website_exploration(name, folder_path="data_dumpster", llm_provider="groq"):
# llm_provider = "groq"
global client
if llm_provider == "openai":
client = OpenAI(api_key=openai_api)
else:
client = Groq(api_key=groq_api)
url = get_website_link(name=name,folder_path=folder_path)
content_home_page = save_website_content(url, folder_path=folder_path)
list_urls = get_all_relevant_links(url, llm_provider=llm_provider)
all_content = [content_home_page]
for relevant_url in list_urls['urls']:
if ".pdf" not in relevant_url:
print(f"Reading through page {relevant_url}")
all_content.append(save_website_content(relevant_url, folder_path=folder_path))
else:
filename = relevant_url.replace('/','_')
download_pdf(relevant_url, f"{folder_path}/pdf/{filename}")
print("TODO: PROCESS PDFs HERE IF PRESENT")
return all_content