Update app.py
Browse files6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412426 unmodified linesfrom datetime import datetime, timedeltaimport reimport os# List of user agents to rotate through_useragent_list = ["Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/91.0.864.59 Safari/537.36","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Edge/91.0.864.59 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36",]API_URL = "https://api-inference.huggingface.co/models/meta-llama/Meta-Llama-3-8B-Instruct"headers = {"Authorization": f"Bearer {os.getenv('HUGGINGFACE_TOKEN')}"}def query_llama(payload):"""Send a query to the Llama model via Hugging Face API"""try:print(f"Payload: {payload}") # Debug: Print payloadresponse = requests.post(API_URL, headers=headers, json=payload)response.raise_for_status()return response.json()except requests.exceptions.RequestException as e:print(f"Error querying Llama model: {e}")return Nonedef google_search(term, num_results=1, lang="en", timeout=30, safe="active", ssl_verify=None, days_back=90):"""Perform a Google search and return results"""print(f"Searching for term: {term}")# Calculate the date rangeend_date = datetime.now()start_date = end_date - timedelta(days=days_back)# Format dates as stringsstart_date_str = start_date.strftime("%Y-%m-%d")end_date_str = end_date.strftime("%Y-%m-%d")# Add the date range to the search termsearch_term = f"{term} financial earnings report after:{start_date_str} before:{end_date_str}"escaped_term = urllib.parse.quote_plus(search_term)start = 0all_results = []max_attempts = num_results * 2 # Allow for some failed attemptswith requests.Session() as session:attempts = 0while len(all_results) < num_results and attempts < max_attempts:try:# Choose a random user agentuser_agent = random.choice(_useragent_list)headers = {'User-Agent': user_agent}resp = session.get(url="https://www.google.com/search",headers=headers,params={"q": search_term,"num": num_results - len(all_results),"hl": lang,"start": start,"safe": safe,},timeout=timeout,verify=ssl_verify,)resp.raise_for_status()soup = BeautifulSoup(resp.text, "html.parser")result_block = soup.find_all("div", attrs={"class": "g"})if not result_block:print("No more results found.")breakfor result in result_block:if len(all_results) >= num_results:breaklink = result.find("a", href=True)if link:link = link["href"]print(f"Found link: {link}")try:webpage = session.get(link, headers=headers, timeout=timeout)webpage.raise_for_status()visible_text = extract_text_from_webpage(webpage.text)all_results.append({"link": link, "text": visible_text})except requests.exceptions.HTTPError as e:if e.response.status_code == 403:print(f"403 Forbidden error for {link}, skipping...")else:print(f"HTTP error {e.response.status_code} for {link}, skipping...")except requests.exceptions.RequestException as e:print(f"Error fetching or processing {link}: {e}")else:print("No link found in result.")start += len(result_block)attempts += 1except requests.exceptions.RequestException as e:print(f"Error fetching search results: {e}")attempts += 1print(f"Total results fetched: {len(all_results)}")return all_resultsdef extract_text_from_webpage(html_content):"""Extract visible text from HTML content"""soup = BeautifulSoup(html_content, 'html.parser')# Remove script and style elementsfor script in soup(["script", "style"]):script.decompose()# Get texttext = soup.get_text()# Break into lines and remove leading and trailing space on eachlines = (line.strip() for line in text.splitlines())# Break multi-headlines into a line eachchunks = (phrase.strip() for line in lines for phrase in line.split(" "))# Drop blank linestext = '\n'.join(chunk for chunk in chunks if chunk)return textdef filter_relevant_content(text):"""Filter out irrelevant content"""# List of keywords related to financial reportskeywords = ['revenue', 'profit', 'earnings', 'financial', 'quarter', 'fiscal', 'growth', 'income', 'loss', 'dividend']# Split the text into sentencessentences = re.split(r'(?<=[.!?])\s+', text)# Filter sentences containing at least one keywordrelevant_sentences = [sentence for sentence in sentences if any(keyword in sentence.lower() for keyword in keywords)]# Join the relevant sentences back into a single stringfiltered_text = ' '.join(relevant_sentences)return filtered_textdef chunk_text(text, max_chunk_size=1000, overlap=100):# List of keywords that might indicate new sectionssection_keywords = ["revenue", "income", "profit", "loss", "expenses", "outlook", "forecast", "quarter", "year"]# Split text into sentencessentences = re.split(r'(?<=[.!?])\s+', text)chunks = []current_chunk = ""for sentence in sentences:if len(current_chunk) + len(sentence) > max_chunk_size:# If adding this sentence exceeds max_chunk_size, start a new chunkchunks.append(current_chunk.strip())current_chunk = sentence + " "elif any(keyword in sentence.lower() for keyword in section_keywords):# If sentence contains a section keyword, start a new chunkif current_chunk:chunks.append(current_chunk.strip())current_chunk = sentence + " "else:current_chunk += sentence + " "# Add the last chunk if it's not emptyif current_chunk:chunks.append(current_chunk.strip())# Add overlapoverlapped_chunks = []for i, chunk in enumerate(chunks):if i > 0:chunk = chunks[i-1][-overlap:] + chunkif i < len(chunks) - 1:chunk = chunk + chunks[i+1][:overlap]overlapped_chunks.append(chunk)return overlapped_chunksdef summarize_financial_news(query):"""Search for financial news, extract relevant content, and summarize"""search_results = google_search(query, num_results=1)all_filtered_text = ""for result in search_results:if result['text']:filtered_text = filter_relevant_content(result['text'])all_filtered_text += filtered_text + "\n\n"if not all_filtered_text:return "No relevant financial information found."# Chunk the filtered textchunks = chunk_text(all_filtered_text, max_chunk_size=3000, overlap=200)summaries = []for chunk in chunks:prompt = f"""You are a financial analyst. Summarize the following text from a financial perspective:{chunk}Provide a detailed, coherent summary focusing on financial implications and analysis."""summary = query_llama({"inputs": prompt, "parameters": {"max_length": 1000}})if summary and isinstance(summary, list) and 'generated_text' in summary[0]:summaries.append(summary[0]['generated_text'])# Combine summariescombined_summary = "\n\n".join(summaries)# Final summarization of combined summariesfinal_prompt = f"""As a financial analyst, provide a coherent and comprehensive summary of the following financial information:{combined_summary}Focus on the most important financial implications and analysis."""final_summary = query_llama({"inputs": final_prompt, "parameters": {"max_length": 3000}})if final_summary and isinstance(final_summary, list) and 'generated_text' in final_summary[0]:return final_summary[0]['generated_text']else:return "Unable to generate summary due to an error."# Gradio Interfaceiface = gr.Interface(fn=summarize_financial_news,inputs=gr.Textbox(lines=2, placeholder="Enter a company name or financial topic..."),outputs="text",title="Financial News Summarizer",description="Enter a company name or financial topic to get a summary of recent financial news.")iface.launch()6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172186 unmodified linesfrom datetime import datetime, timedeltaimport reimport osimport PyPDF2# List of user agents to rotate through_useragent_list = ["Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/91.0.864.59 Safari/537.36","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Edge/91.0.864.59 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36",]API_URL = "https://api-inference.huggingface.co/models/meta-llama/Meta-Llama-3-8B-Instruct"headers = {"Authorization": f"Bearer {os.getenv('HUGGINGFACE_TOKEN')}"}def query_llama(payload):"""Send a query to the Llama model via Hugging Face API"""try:print(f"Payload: {payload}") # Debug: Print payloadresponse = requests.post(API_URL, headers=headers, json=payload)response.raise_for_status()return response.json()except requests.exceptions.RequestException as e:print(f"Error querying Llama model: {e}")return Nonedef google_search(term, num_results=1, lang="en", timeout=30, safe="active", ssl_verify=None, days_back=90):"""Perform a Google search and return results"""print(f"Searching for term: {term}")# Calculate the date rangeend_date = datetime.now()start_date = end_date - timedelta(days=days_back)# Format dates as stringsstart_date_str = start_date.strftime("%Y-%m-%d")end_date_str = end_date.strftime("%Y-%m-%d")# Add the date range to the search termsearch_term = f"{term} financial earnings report after:{start_date_str} before:{end_date_str}"escaped_term = urllib.parse.quote_plus(search_term)start = 0all_results = []max_attempts = num_results * 2 # Allow for some failed attemptswith requests.Session() as session:attempts = 0while len(all_results) < num_results and attempts < max_attempts:try:# Choose a random user agentuser_agent = random.choice(_useragent_list)headers = {'User-Agent': user_agent}resp = session.get(url="https://www.google.com/search",headers=headers,params={"q": search_term,"num": num_results - len(all_results),"hl": lang,"start": start,"safe": safe,},timeout=timeout,verify=ssl_verify,)resp.raise_for_status()soup = BeautifulSoup(resp.text, "html.parser")result_block = soup.find_all("div", attrs={"class": "g"})if not result_block:print("No more results found.")breakfor result in result_block:if len(all_results) >= num_results:breaklink = result.find("a", href=True)if link:link = link["href"]print(f"Found link: {link}")try:webpage = session.get(link, headers=headers, timeout=timeout)webpage.raise_for_status()visible_text = extract_text_from_webpage(webpage.text)all_results.append({"link": link, "text": visible_text})except requests.exceptions.HTTPError as e:if e.response.status_code == 403:print(f"403 Forbidden error for {link}, skipping...")else:print(f"HTTP error {e.response.status_code} for {link}, skipping...")except requests.exceptions.RequestException as e:print(f"Error fetching or processing {link}: {e}")else:print("No link found in result.")start += len(result_block)attempts += 1except requests.exceptions.RequestException as e:print(f"Error fetching search results: {e}")attempts += 1print(f"Total results fetched: {len(all_results)}")return all_resultsdef extract_text_from_webpage(html_content):"""Extract visible text from HTML content"""soup = BeautifulSoup(html_content, 'html.parser')# Remove script and style elementsfor script in soup(["script", "style"]):script.decompose()# Get texttext = soup.get_text()# Break into lines and remove leading and trailing space on eachlines = (line.strip() for line in text.splitlines())# Break multi-headlines into a line eachchunks = (phrase.strip() for line in lines for phrase in line.split(" "))# Drop blank linestext = '\n'.join(chunk for chunk in chunks if chunk)return textdef filter_relevant_content(text):"""Filter out irrelevant content"""# List of keywords related to financial reportskeywords = ['revenue', 'profit', 'earnings', 'financial', 'quarter', 'fiscal', 'growth', 'income', 'loss', 'dividend']# Split the text into sentencessentences = re.split(r'(?<=[.!?])\s+', text)# Filter sentences containing at least one keywordrelevant_sentences = [sentence for sentence in sentences if any(keyword in sentence.lower() for keyword in keywords)]# Join the relevant sentences back into a single stringfiltered_text = ' '.join(relevant_sentences)return filtered_textdef chunk_text(text, max_chunk_size=1000, overlap=100):# List of keywords that might indicate new sectionssection_keywords = ["revenue", "income", "profit", "loss", "expenses", "outlook", "forecast", "quarter", "year"]# Split text into sentencessentences = re.split(r'(?<=[.!?])\s+', text)chunks = []current_chunk = ""for sentence in sentences:if len(current_chunk) + len(sentence) > max_chunk_size:# If adding this sentence exceeds max_chunk_size, start a new chunkchunks.append(current_chunk.strip())current_chunk = sentence + " "elif any(keyword in sentence.lower() for keyword in section_keywords):# If sentence contains a section keyword, start a new chunkif current_chunk:chunks.append(current_chunk.strip())current_chunk = sentence + " "else:current_chunk += sentence + " "# Add the last chunk if it's not emptyif current_chunk:chunks.append(current_chunk.strip())# Add overlapoverlapped_chunks = []for i, chunk in enumerate(chunks):if i > 0:chunk = chunks[i-1][-overlap:] + chunkif i < len(chunks) - 1:chunk = chunk + chunks[i+1][:overlap]overlapped_chunks.append(chunk)return overlapped_chunksdef summarize_text(text, context_instructions):chunks = chunk_text(text, max_chunk_size=3000, overlap=200)summaries = []for chunk in chunks:prompt = f"""You are a financial analyst. Summarize the following text from a financial perspective:{chunk}{context_instructions}"""summary = query_llama({"inputs": prompt, "parameters": {"max_length": 1000}})if summary and isinstance(summary, list) and 'generated_text' in summary[0]:summaries.append(summary[0]['generated_text'])# Combine summariescombined_summary = "\n\n".join(summaries)# Final summarization of combined summariesfinal_prompt = f"""As a financial analyst, provide a coherent and comprehensive summary of the following financial information:{combined_summary}Focus on the most important financial implications and analysis."""final_summary = query_llama({"inputs": final_prompt, "parameters": {"max_length": 3000}})if final_summary and isinstance(final_summary, list) and 'generated_text' in final_summary[0]:return final_summary[0]['generated_text']else:return "Unable to generate summary due to an error."def summarize_financial_news(query, read_pdf=False, pdf=None):"""Search for financial news, extract relevant content, and summarize"""all_filtered_text = ""if read_pdf and pdf is not None:pdf_text = extract_text_from_pdf(pdf)all_filtered_text += pdf_text + "\n\n"else:search_results = google_search(query, num_results=1)for result in search_results:if result['text']:filtered_text = filter_relevant_content(result['text'])all_filtered_text += filtered_text + "\n\n"if not all_filtered_text:return "No relevant financial information found."context_instructions = "Provide a detailed, coherent summary focusing on financial implications and analysis."return summarize_text(all_filtered_text, context_instructions)def extract_text_from_pdf(pdf):"""Extract text from each page of the PDF"""reader = PyPDF2.PdfFileReader(pdf)text = ""for page_num in range(reader.getNumPages()):page = reader.getPage(page_num)text += page.extract_text() + "\n"return text# Gradio Interfacedef interface_function(query, read_pdf, pdf):return summarize_financial_news(query, read_pdf, pdf)iface = gr.Interface(fn=interface_function,inputs=[gr.Textbox(lines=2, placeholder="Enter a company name or financial topic..."),gr.Checkbox(label="Read PDF"),gr.File(label="Upload PDF", type="file")],outputs="text",title="Financial News Summarizer",description="Enter a company name or financial topic to get a summary of recent financial news. Optionally, upload a PDF to summarize its content.")iface.launch()
app.py+193-217