Warisamm748 commited on
Commit
a112641
·
verified ·
1 Parent(s): 4f67aef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +5 -19
app.py CHANGED
@@ -1,7 +1,7 @@
1
  import streamlit as st
2
  import requests
3
  from bs4 import BeautifulSoup
4
- from langchain_core.messages import HumanMessage # แก้ไขตงนี้
5
  from langchain_groq import ChatGroq
6
  import json
7
  import os
@@ -10,11 +10,10 @@ from transformers import pipeline
10
  # --- 0. CONFIGURATION & INITIALIZATION ---
11
 
12
  # การตั้งค่า Groq API Key
13
- # ใน Hugging Face Space ตตั้งค่า GROQ_API_KEY เป็Secret
14
- # Streamlit จะดึงค่านี้มาให้โดยอัตโนมัติ
15
- GROQ_API_KEY = os.getenv('GROQ_API_KEY')
16
  if not GROQ_API_KEY:
17
- st.error("GROQ_API_KEY is not set. Please configure it in your Space Secrets.")
18
  st.stop()
19
 
20
  # Initialize the LLM model
@@ -22,13 +21,10 @@ llm = ChatGroq(api_key=GROQ_API_KEY, model="llama-3.1-8b-instant")
22
 
23
  # --- 1. SCRAPING FUNCTION (Yahoo Finance Only) ---
24
 
25
- # ใช้โค้ด Yahoo Finance ที่เราแก้ไขล่าสุด
26
  def extract_titles_and_summaries(company_name, num_articles=10):
27
  """ดึงหัวข้อและสรุปข่าวจาก Yahoo Finance หน้าหลัก"""
28
  url = 'https://finance.yahoo.com/news/'
29
 
30
- #st.info(f"-> Scraping Yahoo Finance at: {url}")
31
-
32
  try:
33
  # เพิ่ม User-Agent เพื่อหลีกเลี่ยงการถูกบล็อก
34
  response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
@@ -72,7 +68,6 @@ def extract_titles_and_summaries(company_name, num_articles=10):
72
 
73
  # --- 2. ANALYSIS FUNCTIONS ---
74
 
75
- # Function to perform sentiment analysis
76
  def perform_sentiment_analysis(news_data):
77
  """ใช้ Hugging Face Pipeline วิเคราะห์ Sentiment"""
78
  # ใช้ device=-1 เพื่อให้ทำงานบน CPU/อัตโนมัติ
@@ -101,7 +96,6 @@ def perform_sentiment_analysis(news_data):
101
 
102
  return news_data, sentiment_counts
103
 
104
- # Function to extract topics
105
  def extract_topics_with_hf(news_data):
106
  """ใช้ Hugging Face Pipeline สกัดหัวข้อ"""
107
  structured_data = {
@@ -127,14 +121,12 @@ def extract_topics_with_hf(news_data):
127
 
128
  return structured_data
129
 
130
- # Function to extract JSON response from LLM output
131
  def extract_json(response):
132
  try:
133
  return json.loads(response)
134
  except json.JSONDecodeError:
135
  return {}
136
 
137
- # Function to generate a final sentiment summary using LLM
138
  def generate_final_sentiment(news_data, sentiment_counts):
139
  """ใช้ LLM สรุปผลลัพธ์สุดท้าย"""
140
  company_name = news_data["Company"]
@@ -151,12 +143,10 @@ def generate_final_sentiment(news_data, sentiment_counts):
151
 
152
  Respond **ONLY** with a well-structured very concise and short paragraph in plain text, focusing on overall sentiment.
153
  """
154
- # ใช้ HumanMessage จาก langchain_core.messages
155
  response = llm.invoke([HumanMessage(content=prompt)], max_tokens=200)
156
  final_sentiment = response if response else "Sentiment analysis summary not available."
157
  return final_sentiment.content
158
 
159
- # Function to compare articles based on common topics and sentiment variations
160
  def compare_articles(news_data, sentiment_counts):
161
  """ใช้ LLM เปรียบเทียบและสรุปความแตกต่างของข่าว"""
162
  articles = news_data.get("Articles", [])
@@ -216,7 +206,6 @@ def compare_articles(news_data, sentiment_counts):
216
 
217
  # --- 3. STREAMLIT UI IMPLEMENTATION ---
218
 
219
- # ฟังก์ชันแสดงผลลัพธ์ (คัดลอกมาจาก app.py เดิม)
220
  def display_articles(articles):
221
  for i, article in enumerate(articles, start=1):
222
  st.markdown(f"##### **Article {i} ({article['Source']}): {article['Title']}**")
@@ -236,7 +225,6 @@ def display_coverage_differences(coverage_differences):
236
  if coverage_differences:
237
  st.markdown("#### **Coverage Differences:**")
238
  for diff in coverage_differences:
239
- # ปรับปรุงการแสดงผลเพื่อหลีกเลี่ยงการพึ่งพาคีย์ที่อาจไม่มี
240
  comparison = diff.get('Comparison', 'No Comparison Detail')
241
  impact = diff.get('Impact', 'No Impact Detail')
242
  st.write(f"- **{comparison}:** {impact}")
@@ -248,7 +236,6 @@ def display_topic_overlap(topic_overlap):
248
  for article, topics in topic_overlap.get("Unique Topics", {}).items():
249
  st.write(f" - **{article}:** {', '.join(topics)}")
250
 
251
- # ฟังก์ชันหลักในการประมวลผลทั้งหมด
252
  def run_analysis(company_name):
253
  # 1. ดึงข่าว
254
  with st.spinner('1/4 Scraping news from Yahoo Finance...'):
@@ -298,8 +285,7 @@ def run_analysis(company_name):
298
  st.markdown(data.get("Final Sentiment Analysis", "No sentiment analysis available."))
299
  st.markdown("---")
300
 
301
- # ⚠️ ลบส่วน API/Download Hindi Audio/JSON ออก เพราะไม่รองรับในโค้ดนี้
302
- st.json(final_report) # แสดงผล JSON ทั้งหมดให้ user เห็น
303
 
304
  # --- MAIN STREAMLIT APP ---
305
 
 
1
  import streamlit as st
2
  import requests
3
  from bs4 import BeautifulSoup
4
+ from langchain_core.messages import HumanMessage # ใช้ langchain_core เพื่อแก้ปัญหากา Import
5
  from langchain_groq import ChatGroq
6
  import json
7
  import os
 
10
  # --- 0. CONFIGURATION & INITIALIZATION ---
11
 
12
  # การตั้งค่า Groq API Key
13
+ # โคดจะดึงค่าจาก Secret ที่ชื่อ GROQ_API_KEY Hugging Face Space
14
+ GROQ_API_KEY = os.getenv('GROQ_API_KEY')
 
15
  if not GROQ_API_KEY:
16
+ st.error("GROQ_API_KEY is not set. Please configure it in your Space Secrets (Settings > Repository secrets).")
17
  st.stop()
18
 
19
  # Initialize the LLM model
 
21
 
22
  # --- 1. SCRAPING FUNCTION (Yahoo Finance Only) ---
23
 
 
24
  def extract_titles_and_summaries(company_name, num_articles=10):
25
  """ดึงหัวข้อและสรุปข่าวจาก Yahoo Finance หน้าหลัก"""
26
  url = 'https://finance.yahoo.com/news/'
27
 
 
 
28
  try:
29
  # เพิ่ม User-Agent เพื่อหลีกเลี่ยงการถูกบล็อก
30
  response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
 
68
 
69
  # --- 2. ANALYSIS FUNCTIONS ---
70
 
 
71
  def perform_sentiment_analysis(news_data):
72
  """ใช้ Hugging Face Pipeline วิเคราะห์ Sentiment"""
73
  # ใช้ device=-1 เพื่อให้ทำงานบน CPU/อัตโนมัติ
 
96
 
97
  return news_data, sentiment_counts
98
 
 
99
  def extract_topics_with_hf(news_data):
100
  """ใช้ Hugging Face Pipeline สกัดหัวข้อ"""
101
  structured_data = {
 
121
 
122
  return structured_data
123
 
 
124
  def extract_json(response):
125
  try:
126
  return json.loads(response)
127
  except json.JSONDecodeError:
128
  return {}
129
 
 
130
  def generate_final_sentiment(news_data, sentiment_counts):
131
  """ใช้ LLM สรุปผลลัพธ์สุดท้าย"""
132
  company_name = news_data["Company"]
 
143
 
144
  Respond **ONLY** with a well-structured very concise and short paragraph in plain text, focusing on overall sentiment.
145
  """
 
146
  response = llm.invoke([HumanMessage(content=prompt)], max_tokens=200)
147
  final_sentiment = response if response else "Sentiment analysis summary not available."
148
  return final_sentiment.content
149
 
 
150
  def compare_articles(news_data, sentiment_counts):
151
  """ใช้ LLM เปรียบเทียบและสรุปความแตกต่างของข่าว"""
152
  articles = news_data.get("Articles", [])
 
206
 
207
  # --- 3. STREAMLIT UI IMPLEMENTATION ---
208
 
 
209
  def display_articles(articles):
210
  for i, article in enumerate(articles, start=1):
211
  st.markdown(f"##### **Article {i} ({article['Source']}): {article['Title']}**")
 
225
  if coverage_differences:
226
  st.markdown("#### **Coverage Differences:**")
227
  for diff in coverage_differences:
 
228
  comparison = diff.get('Comparison', 'No Comparison Detail')
229
  impact = diff.get('Impact', 'No Impact Detail')
230
  st.write(f"- **{comparison}:** {impact}")
 
236
  for article, topics in topic_overlap.get("Unique Topics", {}).items():
237
  st.write(f" - **{article}:** {', '.join(topics)}")
238
 
 
239
  def run_analysis(company_name):
240
  # 1. ดึงข่าว
241
  with st.spinner('1/4 Scraping news from Yahoo Finance...'):
 
285
  st.markdown(data.get("Final Sentiment Analysis", "No sentiment analysis available."))
286
  st.markdown("---")
287
 
288
+ st.json(final_report)
 
289
 
290
  # --- MAIN STREAMLIT APP ---
291