Update app.py
Browse files9 unmodified lines1011121314156 unmodified lines222324252627274 unmodified lines3023033043053063073083093103113123133146 unmodified lines32132232332432532632713 unmodified lines341342343344345346347101 unmodified lines4494504514524534544554564574584594609 unmodified linesfrom tempfile import NamedTemporaryFilefrom typing import Listfrom bs4 import BeautifulSoupfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_community.vectorstores import FAISSfrom langchain_community.document_loaders import PyPDFLoader6 unmodified linesfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.metrics.pairwise import cosine_similarityhuggingface_token = os.environ.get("HUGGINGFACE_TOKEN")# Memory database to store question-answer pairs274 unmodified linesclean_content = article["title"]full_summary, cleaned_summary = summarize_news_content(clean_content, model)processed_article = {"published_date": article["published_date"],"title": article["title"],"url": article["url"],"content": clean_content,"summary": full_summary,"cleaned_summary": cleaned_summary}processed_articles.append(processed_article)except Exception as e:6 unmodified linesdocs = [Document(page_content=article["cleaned_summary"], metadata={"source": article["url"],"title": article["title"],"published_date": article["published_date"]}) for article in processed_articles]try:13 unmodified linesexcept 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()101 unmodified linesdf['summary'] = df['cleaned_summary']df = df.drop(columns=['cleaned_summary']) # Remove the extra columnwith NamedTemporaryFile(delete=False, suffix='.xlsx') as tmp:excel_path = tmp.namedf.to_excel(excel_path, index=False)return excel_pathdef ask_question(question, temperature, top_p, repetition_penalty, web_search, google_news_rss):global conversation_history9 unmodified lines10111213141516176 unmodified lines24252627282930274 unmodified lines3053063073083093103113123133143153163173183193206 unmodified lines32732832933033133233333413 unmodified lines348349350351352353101 unmodified lines4554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984999 unmodified linesfrom tempfile import NamedTemporaryFilefrom typing import Listfrom bs4 import BeautifulSoupfrom langchain.prompts import PromptTemplatefrom langchain.chains import LLMChainfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_community.vectorstores import FAISSfrom langchain_community.document_loaders import PyPDFLoader6 unmodified linesfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.metrics.pairwise import cosine_similarityhuggingface_token = os.environ.get("HUGGINGFACE_TOKEN")# Memory database to store question-answer pairs274 unmodified linesclean_content = article["title"]full_summary, cleaned_summary = summarize_news_content(clean_content, model)relevance_score = calculate_relevance_score(cleaned_summary, model)processed_article = {"published_date": article["published_date"],"title": article["title"],"url": article["url"],"content": clean_content,"summary": full_summary,"cleaned_summary": cleaned_summary,"relevance_score": relevance_score}processed_articles.append(processed_article)except Exception as e:6 unmodified linesdocs = [Document(page_content=article["cleaned_summary"], metadata={"source": article["url"],"title": article["title"],"published_date": article["published_date"],"relevance_score": article["relevance_score"]}) for article in processed_articles]try:13 unmodified linesexcept 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()101 unmodified linesdf['summary'] = df['cleaned_summary']df = df.drop(columns=['cleaned_summary']) # Remove the extra column# Reorder columns to put relevance_score after summarycolumns = ['published_date', 'title', 'url', 'content', 'summary', 'relevance_score']df = df[columns]with NamedTemporaryFile(delete=False, suffix='.xlsx') as tmp:excel_path = tmp.namedf.to_excel(excel_path, index=False)return excel_pathdef calculate_relevance_score(summary, model):prompt_template = PromptTemplate(input_variables=["summary"],template="""You are a financial analyst tasked with providing a relevance score to news summaries.The score should be based on the financial significance and impact of the news.Use the following scoring guide:- 0.00-0.20: Not relevant to finance or economics- 0.21-0.40: Slightly relevant, but minimal financial impact- 0.41-0.60: Moderately relevant, some financial implications- 0.61-0.80: Highly relevant, significant financial impact- 0.81-1.00: Extremely relevant, major financial implicationsProvide a score between 0.00 and 1.00, where 0.00 is not relevant at all, and 1.00 is extremely relevant from a financial perspective.Summary: {summary}Relevance Score:""")chain = LLMChain(llm=model, prompt=prompt_template)response = chain.run(summary=summary)try:score = float(response.strip())return min(max(score, 0.00), 1.00) # Ensure the score is between 0.00 and 1.00except ValueError:print(f"Error parsing relevance score: {response}")return 0.00def ask_question(question, temperature, top_p, repetition_penalty, web_search, google_news_rss):global conversation_history
app.py+42-3