Update app.py
Browse files364 unmodified lines3653663673683693703713723733743753763773783798 unmodified lines3883893903913923933948 unmodified lines40340440540640740840941041141241316 unmodified lines4304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744752 unmodified lines4784794804814824834844854864874884894904914924934944954964974984995005015025035045055065074 unmodified lines512513514515516517518244 unmodified lines763764765766767768769770771772773774775776777778779780364 unmodified linesmodel = get_model(temperature, top_p, repetition_penalty)embed = get_embeddings()if news_source == "Google News RSS":articles = fetch_google_news_rss(query)elif news_source == "Golomt Bank":articles = fetch_golomt_bank_news()else:return "Invalid news source selected."if not articles:return f"No news articles found for the given {news_source}."processed_articles = []8 unmodified linesfull_summary, cleaned_summary = summarize_news_content(clean_content, model)relevance_score = calculate_relevance_score(cleaned_summary, model)print(f"Relevance score for article '{article['title']}': {relevance_score}") # Debug printprocessed_article = {"published_date": article["published_date"],8 unmodified linesexcept Exception as e:print(f"Error processing article: {str(e)}")# Debug printprint("Processed articles:")for article in processed_articles:print(f"Title: {article['title']}, Score: {article['relevance_score']}")if not processed_articles:return f"Failed to process any news articles from {news_source}. Please try again or check the summarization process."16 unmodified lines# Update news_database for excel exportglobal news_databasenews_database = processed_articles # Directly assign the processed articlesprint("Updated news_database:")for article in news_database:print(f"Title: {article['title']}, Score: {article['relevance_score']}")return f"Processed and added {len(processed_articles)} news articles from {news_source} to the database."except Exception as e:return f"Error adding articles to the database: {str(e)}"def fetch_articles_from_page(url):response = requests.get(url)response.raise_for_status()soup = BeautifulSoup(response.content, 'html.parser')articles = soup.find_all('div', class_='entry-post gt-box-shadow-2')return articles, soupdef fetch_articles_from_page(url):response = requests.get(url)response.raise_for_status()soup = BeautifulSoup(response.content, 'html.parser')articles = soup.find_all('div', class_='entry-post gt-box-shadow-2')return articles, soupdef extract_articles(articles):article_data = []for article in articles:title_div = article.find('h2', class_='entry-title')title = title_div.get_text(strip=True) if title_div else "No Title"date_div = article.find('div', class_='entry-date gt-meta')date = date_div.get_text(strip=True) if date_div else "No Date"link_tag = article.find('a')link = link_tag['href'] if link_tag else "No Link"if not link.startswith('http'):link = "https://golomtbank.com" + linkarticle_response = requests.get(link)article_response.raise_for_status()article_soup = BeautifulSoup(article_response.content, 'html.parser')article_content_div = article_soup.find('div', class_='entry-content')article_content = article_content_div.get_text(strip=True) if article_content_div else "No content found"article_data.append({'title': title,'date': date,2 unmodified lines})return article_datadef fetch_golomt_bank_news(num_results=20):base_url = "https://golomtbank.com/en/rnews"current_page_url = base_urlall_articles = []try:while len(all_articles) < num_results:print(f"Fetching articles from: {current_page_url}")articles, soup = fetch_articles_from_page(current_page_url)if not articles:print("No articles found on this page.")breakall_articles.extend(extract_articles(articles))print(f"Total articles fetched so far: {len(all_articles)}")if len(all_articles) >= num_results:all_articles = all_articles[:num_results]breaknext_page_link = soup.find('a', class_='next')if not next_page_link:print("No next page link found.")breakcurrent_page_url = next_page_link['href']if not current_page_url.startswith('http'):current_page_url = "https://golomtbank.com" + current_page_urlreturn [{4 unmodified lines} for article in all_articles]except Exception as e:print(f"Error fetching Golomt Bank news: {str(e)}")return []def export_news_to_excel():244 unmodified linesrepetition_penalty_slider = gr.Slider(label="Repetition Penalty", minimum=1.0, maximum=2.0, value=1.0, step=0.1)web_search_checkbox = gr.Checkbox(label="Enable Web Search", value=False)google_news_rss_checkbox = gr.Checkbox(label="Google News RSS", value=False)with gr.Row():news_source_dropdown = gr.Dropdown(choices=["Google News RSS", "Golomt Bank"],label="Select News Source",value="Google News RSS")news_query_input = gr.Textbox(label="Enter news query (for Google News RSS)")fetch_news_button = gr.Button("Fetch News")news_fetch_output = gr.Textbox(label="News Fetch Status")def chat(question, history, temperature, top_p, repetition_penalty, web_search, google_news_rss):answer = ask_question(question, temperature, top_p, repetition_penalty, web_search, google_news_rss)history.append((question, answer))364 unmodified lines3653663673683693703713723733743753763778 unmodified lines3863873883893903918 unmodified lines40040140240340440516 unmodified lines4224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854862 unmodified lines4894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215224 unmodified lines527528529530531532533244 unmodified lines778779780781782783784785786787788789790791792793794795796797798799800801802364 unmodified linesmodel = get_model(temperature, top_p, repetition_penalty)embed = get_embeddings()if news_source in website_configs:articles = fetch_news_from_website(news_source)else:return f"Invalid news source selected: {news_source}"if not articles:return f"No news articles found for {news_source}."processed_articles = []8 unmodified linesfull_summary, cleaned_summary = summarize_news_content(clean_content, model)relevance_score = calculate_relevance_score(cleaned_summary, model)processed_article = {"published_date": article["published_date"],8 unmodified linesexcept Exception as e:print(f"Error processing article: {str(e)}")if not processed_articles:return f"Failed to process any news articles from {news_source}. Please try again or check the summarization process."16 unmodified lines# Update news_database for excel exportglobal news_databasenews_database = processed_articlesreturn f"Processed and added {len(processed_articles)} news articles from {news_source} to the database."except Exception as e:return f"Error adding articles to the database: {str(e)}"website_configs = {"Golomt Bank": {"base_url": "https://golomtbank.com/en/rnews","article_selector": 'div.entry-post.gt-box-shadow-2',"title_selector": 'h2.entry-title',"date_selector": 'div.entry-date.gt-meta',"link_selector": 'a',"content_selector": 'div.entry-content',"next_page_selector": 'a.next',"url_prefix": "https://golomtbank.com"},"Bank of America": {"base_url": "https://newsroom.bankofamerica.com/content/newsroom/press-releases.html","article_selector": 'div.views-row',"title_selector": 'span.field-content',"date_selector": 'span.date-display-single',"link_selector": 'a',"content_selector": 'div.field-name-body',"next_page_selector": 'li.pager-next a',"url_prefix": "https://newsroom.bankofamerica.com"},# Add more banks as needed}def fetch_articles_from_page(url, config):response = requests.get(url)response.raise_for_status()soup = BeautifulSoup(response.content, 'html.parser')articles = soup.find_all(config['article_selector'].split('.')[0], class_=config['article_selector'].split('.')[-1])return articles, soupdef extract_articles(articles, config):article_data = []for article in articles:title_div = article.find(config['title_selector'].split('.')[0], class_=config['title_selector'].split('.')[-1])title = title_div.get_text(strip=True) if title_div else "No Title"date_div = article.find(config['date_selector'].split('.')[0], class_=config['date_selector'].split('.')[-1])date = date_div.get_text(strip=True) if date_div else "No Date"link_tag = article.find(config['link_selector'])link = link_tag['href'] if link_tag else "No Link"if not link.startswith('http'):link = config['url_prefix'] + linkarticle_response = requests.get(link)article_response.raise_for_status()article_soup = BeautifulSoup(article_response.content, 'html.parser')article_content_div = article_soup.find(config['content_selector'].split('.')[0], class_=config['content_selector'].split('.')[-1])article_content = article_content_div.get_text(strip=True) if article_content_div else "No content found"article_data.append({'title': title,'date': date,2 unmodified lines})return article_datadef fetch_news_from_website(website_key, num_results=20):config = website_configs.get(website_key)if not config:return f"No configuration found for website: {website_key}"base_url = config['base_url']current_page_url = base_urlall_articles = []try:while len(all_articles) < num_results:print(f"Fetching articles from: {current_page_url}")articles, soup = fetch_articles_from_page(current_page_url, config)if not articles:print("No articles found on this page.")breakall_articles.extend(extract_articles(articles, config))print(f"Total articles fetched so far: {len(all_articles)}")if len(all_articles) >= num_results:all_articles = all_articles[:num_results]breaknext_page_link = soup.find(config['next_page_selector'])if not next_page_link:print("No next page link found.")breakcurrent_page_url = next_page_link['href']if not current_page_url.startswith('http'):current_page_url = config['url_prefix'] + current_page_urlreturn [{4 unmodified lines} for article in all_articles]except Exception as e:print(f"Error fetching news from {website_key}: {str(e)}")return []def export_news_to_excel():244 unmodified linesrepetition_penalty_slider = gr.Slider(label="Repetition Penalty", minimum=1.0, maximum=2.0, value=1.0, step=0.1)web_search_checkbox = gr.Checkbox(label="Enable Web Search", value=False)google_news_rss_checkbox = gr.Checkbox(label="Google News RSS", value=False)with gr.Row():bank_dropdown = gr.Dropdown(choices=list(website_configs.keys()),label="Select Bank",value=list(website_configs.keys())[0])fetch_news_button = gr.Button("Fetch Bank News")news_fetch_output = gr.Textbox(label="News Fetch Status")submit_button.click(chat, inputs=[question_input, chatbot, temperature_slider, top_p_slider, repetition_penalty_slider, web_search_checkbox, google_news_rss_checkbox], outputs=[question_input, chatbot])fetch_news_button.click(fetch_bank_news,inputs=[bank_dropdown, temperature_slider, top_p_slider, repetition_penalty_slider],outputs=news_fetch_output)def chat(question, history, temperature, top_p, repetition_penalty, web_search, google_news_rss):answer = ask_question(question, temperature, top_p, repetition_penalty, web_search, google_news_rss)history.append((question, answer))
app.py+68-46