Sooteemon commited on
Commit
56e70fe
·
verified ·
1 Parent(s): f72fd82

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +11 -103
app.py CHANGED
@@ -5,14 +5,7 @@ from sentiment_analyzer import NewsAnalyzer # Import new class
5
  import time
6
  from collections import Counter # For counting themes/impacts
7
 
8
- # --- MODIFIED BLOCK 1 ---
9
- # เราจะโหลด Scraper (เบา) แต่จะยังไม่โหลด Analyzer (หนัก)
10
- print("Initializing Yahoo Finance News Analyzer...")
11
- scraper = YahooFinanceScraper()
12
- analyzer = None # <-- ตั้งเป็น None ก่อน จะโหลดเมื่อถูกเรียกใช้ครั้งแรก
13
- # --- END MODIFIED BLOCK ---
14
-
15
-
16
  def get_sentiment_color(sentiment):
17
  """กำหนดสีตาม sentiment"""
18
  colors = { "Positive": "🟢", "Negative": "🔴", "Neutral": "🟡" }
@@ -24,23 +17,11 @@ def get_impact_color(impact):
24
  return colors.get(impact, "⚪")
25
 
26
 
 
27
  def analyze_news(search_type, search_input, num_articles):
28
  """
29
  ฟังก์ชันหลักในการวิเคราะห์ข่าว
30
  """
31
-
32
- # --- MODIFIED BLOCK 2: LAZY LOADING ---
33
- # ตรวจสอบว่า analyzer ถูกโหลดหรือยัง
34
- global analyzer
35
- if analyzer is None:
36
- # ถ้ายัง ให้แสดงสถานะว่ากำลังโหลด
37
- yield "⌛ กำลังโหลดโมเดล AI (ครั้งแรก)...", None, "⌛ กำลังโหลดโมเดล AI (ครั้งแรก)..."
38
- print("Analyzer not loaded. Initializing NewsAnalyzer (lazy)...")
39
- # นี่คือจุดที่จะโหลดโมเดล (ใช้เวลา 1-2 นาทีในครั้งแรก)
40
- analyzer = NewsAnalyzer()
41
- print("Analyzer loaded successfully.")
42
- # --- END MODIFIED BLOCK ---
43
-
44
  try:
45
  yield "กำลังดึงข่าว...", None, None
46
 
@@ -65,7 +46,7 @@ def analyze_news(search_type, search_input, num_articles):
65
 
66
  results = analyzer.analyze_batch(news_list)
67
 
68
- # (ส่วนที่เหลือของฟังก์ชันเหมือนเดิม)
69
  total = len(results)
70
  positive = sum(1 for r in results if r['sentiment'] == 'Positive')
71
  negative = sum(1 for r in results if r['sentiment'] == 'Negative')
@@ -90,22 +71,23 @@ def analyze_news(search_type, search_input, num_articles):
90
  - 🔴 Negative: {negative} ({negative/total*100:.1f}%)
91
  - 🟡 Neutral: {neutral} ({neutral/total*100:.1f}%)
92
 
93
- ---
94
-
95
  ### 📌 สรุปหัวข้อ (Themes)
96
  """
97
  for theme, count in theme_counts.most_common():
98
  summary += f"- **{theme}:** {count} รายการ ({count/total*100:.1f}%)\n"
99
 
100
- summary += "\n---\n" # เพิ่มเส้นคั่น
101
-
102
  summary += "\n### ⚡ สรุปผลกระทบ (Impact)\n"
103
  for impact, count in impact_counts.most_common():
104
  emoji = get_impact_color(impact)
105
  summary += f"- {emoji} **{impact}:** {count} รายการ ({count/total*100:.1f}%)\n"
106
-
 
 
107
  summary += "\n\n---\n\n## 📰 รายละเอียดแต่ละข่าว\n\n"
 
 
108
  detailed_results = ""
 
109
 
110
  for i, result in enumerate(results, 1):
111
  s_emoji = get_sentiment_color(result['sentiment'])
@@ -120,6 +102,7 @@ def analyze_news(search_type, search_input, num_articles):
120
  [🔗 อ่านต่อ]({result['link']})
121
  ---"""
122
 
 
123
  df_data = []
124
  for result in results:
125
  df_data.append({
@@ -141,79 +124,4 @@ def analyze_news(search_type, search_input, num_articles):
141
  error_msg = f"❌ เกิดข้อผิดพลาด: {str(e)}"
142
  yield error_msg, None, error_msg
143
 
144
- # (ส่วน Interface (with gr.Blocks...) ... ไม่ต้องแก้)
145
- with gr.Blocks(title="Yahoo Finance News Analyzer", theme=gr.themes.Soft()) as demo:
146
- gr.Markdown("""
147
- # 📈 Yahoo Finance News Analyzer
148
- วิเคราะห์ข่าวการเงินจาก Yahoo Finance ด้วย AI แบบครบวงจร
149
-
150
- 🔍 **ฟีเจอร์:**
151
- - วิเคราะห์ Sentiment (ความรู้สึก)
152
- - วิเคราะห์ Theme (หัวข้อข่าว)
153
- - วิเคราะห์ Impact (ผลกระทบ: โอกาส หรือ ความเสี่ยง)
154
- - ให้คะแนนความมั่นใจและคำอธิบาย
155
- - รองรับค้นหาตาม Stock Symbol และ Keyword
156
- """)
157
-
158
- with gr.Row():
159
- with gr.Column(scale=1):
160
- search_type = gr.Radio(
161
- choices=["Latest News", "Stock Symbol", "Keyword"],
162
- value="Latest News",
163
- label="ประเภทการค้นหา"
164
- )
165
- search_input = gr.Textbox(
166
- label="Ticker Symbol / Keyword",
167
- placeholder="เช่น AAPL, TSLA, AI, cryptocurrency",
168
- info="ใส่เฉพาะเมื่อเลือก Stock Symbol หรือ Keyword"
169
- )
170
- num_articles = gr.Slider(
171
- minimum=5,
172
- maximum=20,
173
- value=10,
174
- step=1,
175
- label="จำนวนข่าว"
176
- )
177
- analyze_btn = gr.Button("🔍 วิเคราะห์ข่าว", variant="primary", size="lg")
178
- status = gr.Textbox(label="สถานะ", interactive=False)
179
-
180
- with gr.Column(scale=2):
181
- results_md = gr.Markdown("### กดปุ่ม 'วิเคราะห์ข่าว' เพื่อเริ่มต้น")
182
-
183
- with gr.Row():
184
- results_table = gr.Dataframe(
185
- label="📊 ตารางสรุปผล",
186
- wrap=True
187
- )
188
-
189
- gr.Markdown("""
190
- ---
191
- ### 💡 วิธีใช้งาน:
192
- 1. เลือกประเภทการค้นหา (ข่าวล่าสุด / หุ้นเฉพาะ / คำค้นหา)
193
- 2. ใส่ ticker symbol หรือ keyword (ถ้าต้องการ)
194
- 3. เลือกจำนวนข่าวที่ต้องการวิเคราะห์
195
- 4. กดปุ่ม "วิเคราะห์ข่าว"
196
-
197
- ### 🎯 ตัวอย่าง Stock Symbols:
198
- - **AAPL** - Apple Inc.
199
- - **TSLA** - Tesla
200
- - **NVDA** - Nvidia
201
- - **MSFT** - Microsoft
202
- - **GOOGL** - Google
203
-
204
- ### 📌 หมายเหตุ:
205
- - **Sentiment:** Positive (ดี), Negative (แย่), Neutral (กลาง)
206
- - **Theme:** หัวข้อหลักของข่าว (เช่น ผลประกอบการ, สินค้าใหม่)
207
- - **Impact:** ผลกระทบต่อบริษัท (🟢 Opportunity - โอกาส, 🔴 Risk - ความเสี่ยง)
208
- """)
209
-
210
- analyze_btn.click(
211
- fn=analyze_news,
212
- inputs=[search_type, search_input, num_articles],
213
- outputs=[results_md, results_table, status]
214
- )
215
-
216
- # Launch app
217
- if __name__ == "__main__":
218
- demo.queue()
219
- demo.
 
5
  import time
6
  from collections import Counter # For counting themes/impacts
7
 
8
+ # (ฟังก์ชัน get_sentiment_color และ get_impact_color ... ไม่ต้องแก้)
 
 
 
 
 
 
 
9
  def get_sentiment_color(sentiment):
10
  """กำหนดสีตาม sentiment"""
11
  colors = { "Positive": "🟢", "Negative": "🔴", "Neutral": "🟡" }
 
17
  return colors.get(impact, "⚪")
18
 
19
 
20
+ # --- คัดลอกทับเฉพาะฟังก์ชันนี้ครับ ---
21
  def analyze_news(search_type, search_input, num_articles):
22
  """
23
  ฟังก์ชันหลักในการวิเคราะห์ข่าว
24
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  try:
26
  yield "กำลังดึงข่าว...", None, None
27
 
 
46
 
47
  results = analyzer.analyze_batch(news_list)
48
 
49
+ # Create summary statistics
50
  total = len(results)
51
  positive = sum(1 for r in results if r['sentiment'] == 'Positive')
52
  negative = sum(1 for r in results if r['sentiment'] == 'Negative')
 
71
  - 🔴 Negative: {negative} ({negative/total*100:.1f}%)
72
  - 🟡 Neutral: {neutral} ({neutral/total*100:.1f}%)
73
 
 
 
74
  ### 📌 สรุปหัวข้อ (Themes)
75
  """
76
  for theme, count in theme_counts.most_common():
77
  summary += f"- **{theme}:** {count} รายการ ({count/total*100:.1f}%)\n"
78
 
 
 
79
  summary += "\n### ⚡ สรุปผลกระทบ (Impact)\n"
80
  for impact, count in impact_counts.most_common():
81
  emoji = get_impact_color(impact)
82
  summary += f"- {emoji} **{impact}:** {count} รายการ ({count/total*100:.1f}%)\n"
83
+
84
+ # --- (MODIFIED BLOCK) ---
85
+ # ย้ายเส้นคั่นและหัวข้อ "รายละเอียด" มาไว้ใน summary
86
  summary += "\n\n---\n\n## 📰 รายละเอียดแต่ละข่าว\n\n"
87
+
88
+ # Create detailed results (เริ่มต้นด้วยสตริงว่าง)
89
  detailed_results = ""
90
+ # --- (END MODIFIED BLOCK) ---
91
 
92
  for i, result in enumerate(results, 1):
93
  s_emoji = get_sentiment_color(result['sentiment'])
 
102
  [🔗 อ่านต่อ]({result['link']})
103
  ---"""
104
 
105
+ # Create DataFrame for table view
106
  df_data = []
107
  for result in results:
108
  df_data.append({
 
124
  error_msg = f"❌ เกิดข้อผิดพลาด: {str(e)}"
125
  yield error_msg, None, error_msg
126
 
127
+ # (โค้ดส่วน Interface (with gr.Blocks...) ... ไม่ต้องแก้)