Spaces:
openfree
/
Running on CPU Upgrade

openfree commited on
Commit
db98ece
·
verified ·
1 Parent(s): 7732551

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +124 -1
app.py CHANGED
@@ -28,7 +28,7 @@ def create_article_components(max_results):
28
  return article_components
29
 
30
  API_KEY = os.getenv("SERPHOUSE_API_KEY")
31
- # hf_client = InferenceClient("CohereForAI/c4ai-command-r-plus-08-2024", token=os.getenv("HF_TOKEN"))
32
 
33
  # 국가별 언어 코드 매핑
34
  COUNTRY_LANGUAGES = {
@@ -40,6 +40,7 @@ COUNTRY_LANGUAGES = {
40
  "Germany": "de",
41
  "France": "fr",
42
  "Japan": "ja",
 
43
  "China": "zh",
44
  "India": "hi",
45
  "Brazil": "pt",
@@ -110,6 +111,7 @@ COUNTRY_LOCATIONS = {
110
  "Germany": "Germany",
111
  "France": "France",
112
  "Japan": "Japan",
 
113
  "China": "China",
114
  "India": "India",
115
  "Brazil": "Brazil",
@@ -308,6 +310,51 @@ def serphouse_search(query, country):
308
  response_data = search_serphouse(query, country)
309
  return format_results_from_raw(response_data)
310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
  css = """
312
  footer {visibility: hidden;}
313
 
@@ -618,4 +665,80 @@ with gr.Blocks(theme="Nymbo/Nymbo_Theme", css=css, title="NewsAI 서비스") as
618
  outputs=global_search_outputs
619
  )
620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
621
  iface.launch(auth=("it1","chosun1"))
 
28
  return article_components
29
 
30
  API_KEY = os.getenv("SERPHOUSE_API_KEY")
31
+ hf_client = InferenceClient("CohereForAI/c4ai-command-r-plus-08-2024", token=os.getenv("HF_TOKEN"))
32
 
33
  # 국가별 언어 코드 매핑
34
  COUNTRY_LANGUAGES = {
 
40
  "Germany": "de",
41
  "France": "fr",
42
  "Japan": "ja",
43
+ # "South Korea": "ko",
44
  "China": "zh",
45
  "India": "hi",
46
  "Brazil": "pt",
 
111
  "Germany": "Germany",
112
  "France": "France",
113
  "Japan": "Japan",
114
+ # "South Korea": "South Korea",
115
  "China": "China",
116
  "India": "India",
117
  "Brazil": "Brazil",
 
310
  response_data = search_serphouse(query, country)
311
  return format_results_from_raw(response_data)
312
 
313
+
314
+ # Hacker News API 관련 함수 추가
315
+ def get_hn_item(item_id):
316
+ """개별 아이템 정보 가져오기"""
317
+ try:
318
+ response = requests.get(f"https://hacker-news.firebaseio.com/v0/item/{item_id}.json")
319
+ return response.json()
320
+ except:
321
+ return None
322
+
323
+ def get_recent_stories():
324
+ """최신 스토리 가져오기"""
325
+ try:
326
+ # newstories 엔드포인트로 최신 스토리 ID 목록 가져오기
327
+ response = requests.get("https://hacker-news.firebaseio.com/v0/newstories.json")
328
+ story_ids = response.json()
329
+
330
+ # 24시간 이내 스토리만 필터링
331
+ recent_stories = []
332
+ current_time = datetime.now().timestamp()
333
+ day_ago = current_time - (24 * 60 * 60)
334
+
335
+ for story_id in story_ids:
336
+ story = get_hn_item(story_id)
337
+ if story and 'time' in story and story['time'] > day_ago:
338
+ recent_stories.append(story)
339
+
340
+ # 충분한 스토리를 모았으면 중단
341
+ if len(recent_stories) >= 100: # 최대 100개로 제한
342
+ break
343
+
344
+ return recent_stories
345
+ except Exception as e:
346
+ print(f"Error fetching HN stories: {str(e)}")
347
+ return []
348
+
349
+ def format_hn_time(timestamp):
350
+ """Unix timestamp를 읽기 쉬운 형식으로 변환"""
351
+ try:
352
+ dt = datetime.fromtimestamp(timestamp)
353
+ return dt.strftime("%Y-%m-%d %H:%M:%S")
354
+ except:
355
+ return "Unknown time"
356
+
357
+
358
  css = """
359
  footer {visibility: hidden;}
360
 
 
665
  outputs=global_search_outputs
666
  )
667
 
668
+ # 탭 구현 부분에 다음 코드 추가
669
+ with gr.Tab("AI 리포터"):
670
+ gr.Markdown("지난 24시간 동안의 Hacker News 포스트를 보여줍니다.")
671
+
672
+ with gr.Column():
673
+ refresh_button = gr.Button("새로고침", variant="primary")
674
+ status_message_hn = gr.Markdown("")
675
+
676
+ # 결과 출력 영역
677
+ with gr.Column(elem_id="hn_results_area"):
678
+ hn_articles_state = gr.State([])
679
+
680
+ hn_article_components = []
681
+ for i in range(100): # 최대 100개 표시
682
+ with gr.Group(visible=False) as article_group:
683
+ title = gr.Markdown()
684
+ info = gr.Markdown()
685
+
686
+ hn_article_components.append({
687
+ 'group': article_group,
688
+ 'title': title,
689
+ 'info': info,
690
+ 'index': i,
691
+ })
692
+
693
+ def refresh_hn_stories():
694
+ """Hacker News 스토리 새로고침"""
695
+ status_msg = "Hacker News 포스트를 가져오는 중..."
696
+
697
+ outputs = [gr.update(value=status_msg, visible=True)]
698
+
699
+ # 모든 컴포넌트 초기화
700
+ for _ in hn_article_components:
701
+ outputs.extend([
702
+ gr.update(visible=False),
703
+ gr.update(),
704
+ gr.update()
705
+ ])
706
+
707
+ # 최신 스토리 가져오기
708
+ stories = get_recent_stories()
709
+
710
+ # 결과 업데이트
711
+ outputs = [gr.update(value=f"총 {len(stories)}개의 포스트를 찾았습니다.", visible=True)]
712
+
713
+ for idx, comp in enumerate(hn_article_components):
714
+ if idx < len(stories):
715
+ story = stories[idx]
716
+ outputs.extend([
717
+ gr.update(visible=True),
718
+ gr.update(value=f"### [{story.get('title', 'Untitled')}]({story.get('url', '#')})"),
719
+ gr.update(value=f"**작성자:** {story.get('by', 'unknown')} | **시간:** {format_hn_time(story.get('time', 0))} | **점수:** {story.get('score', 0)} | **댓글:** {len(story.get('kids', []))}개")
720
+ ])
721
+ else:
722
+ outputs.extend([
723
+ gr.update(visible=False),
724
+ gr.update(),
725
+ gr.update()
726
+ ])
727
+
728
+ return outputs
729
+
730
+ # 이벤트 연결
731
+ hn_outputs = [status_message_hn]
732
+ for comp in hn_article_components:
733
+ hn_outputs.extend([
734
+ comp['group'],
735
+ comp['title'],
736
+ comp['info']
737
+ ])
738
+
739
+ refresh_button.click(
740
+ refresh_hn_stories,
741
+ outputs=hn_outputs
742
+ )
743
+
744
  iface.launch(auth=("it1","chosun1"))