Spaces:
openfree
/
Running on CPU Upgrade

ginipick commited on
Commit
cc1a9a6
ยท
verified ยท
1 Parent(s): c8695fd

Update app-backup2.py

Browse files
Files changed (1) hide show
  1. app-backup2.py +535 -636
app-backup2.py CHANGED
@@ -3,12 +3,21 @@ import requests
3
  import json
4
  import os
5
  from datetime import datetime, timedelta
6
- from huggingface_hub import InferenceClient
7
-
 
 
 
8
  from bs4 import BeautifulSoup
9
- import concurrent.futures
10
- import time
11
- import re
 
 
 
 
 
 
12
 
13
  MAX_COUNTRY_RESULTS = 100 # ๊ตญ๊ฐ€๋ณ„ ์ตœ๋Œ€ ๊ฒฐ๊ณผ ์ˆ˜
14
  MAX_GLOBAL_RESULTS = 1000 # ์ „์„ธ๊ณ„ ์ตœ๋Œ€ ๊ฒฐ๊ณผ ์ˆ˜
@@ -33,13 +42,12 @@ def create_article_components(max_results):
33
  return article_components
34
 
35
  API_KEY = os.getenv("SERPHOUSE_API_KEY")
36
- hf_client = InferenceClient("CohereForAI/c4ai-command-r-plus-08-2024", token=os.getenv("HF_TOKEN"))
37
 
38
  # ๊ตญ๊ฐ€๋ณ„ ์–ธ์–ด ์ฝ”๋“œ ๋งคํ•‘
39
  COUNTRY_LANGUAGES = {
40
  "United States": "en",
41
  "United Kingdom": "en",
42
- "Taiwan": "zh-TW", # ๋Œ€๋งŒ์–ด(๋ฒˆ์ฒด ์ค‘๊ตญ์–ด)
43
  "Canada": "en",
44
  "Australia": "en",
45
  "Germany": "de",
@@ -109,7 +117,7 @@ COUNTRY_LANGUAGES = {
109
  COUNTRY_LOCATIONS = {
110
  "United States": "United States",
111
  "United Kingdom": "United Kingdom",
112
- "Taiwan": "Taiwan", # ๊ตญ๊ฐ€๋ช… ์‚ฌ์šฉ
113
  "Canada": "Canada",
114
  "Australia": "Australia",
115
  "Germany": "Germany",
@@ -176,8 +184,7 @@ COUNTRY_LOCATIONS = {
176
  "Iceland": "Iceland"
177
  }
178
 
179
- MAJOR_COUNTRIES = list(COUNTRY_LOCATIONS.keys())
180
-
181
  # ๋™์•„์‹œ์•„ ์ง€์—ญ
182
  COUNTRY_LANGUAGES_EAST_ASIA = {
183
  "Taiwan": "zh-TW",
@@ -352,24 +359,20 @@ REGIONS = [
352
  "์•„๋ฉ”๋ฆฌ์นด"
353
  ]
354
 
 
 
355
  def translate_query(query, country):
356
  try:
357
- # ์˜์–ด ์ž…๋ ฅ ํ™•์ธ
358
  if is_english(query):
359
- print(f"์˜์–ด ๊ฒ€์ƒ‰์–ด ๊ฐ์ง€ - ์›๋ณธ ์‚ฌ์šฉ: {query}")
360
  return query
361
 
362
- # ์„ ํƒ๋œ ๊ตญ๊ฐ€๊ฐ€ ๋ฒˆ์—ญ ์ง€์› ๊ตญ๊ฐ€์ธ ๊ฒฝ์šฐ
363
  if country in COUNTRY_LANGUAGES:
364
- # South Korea ์„ ํƒ์‹œ ํ•œ๊ธ€ ์ž…๋ ฅ์€ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉ
365
  if country == "South Korea":
366
- print(f"ํ•œ๊ตญ ์„ ํƒ - ์›๋ณธ ์‚ฌ์šฉ: {query}")
367
  return query
368
 
369
  target_lang = COUNTRY_LANGUAGES[country]
370
- print(f"๋ฒˆ์—ญ ์‹œ๋„: {query} -> {country}({target_lang})")
371
 
372
- url = f"https://translate.googleapis.com/translate_a/single"
373
  params = {
374
  "client": "gtx",
375
  "sl": "auto",
@@ -378,9 +381,12 @@ def translate_query(query, country):
378
  "q": query
379
  }
380
 
381
- response = requests.get(url, params=params)
 
 
 
 
382
  translated_text = response.json()[0][0][0]
383
- print(f"๋ฒˆ์—ญ ์™„๋ฃŒ: {query} -> {translated_text} ({country})")
384
  return translated_text
385
 
386
  return query
@@ -389,6 +395,8 @@ def translate_query(query, country):
389
  print(f"๋ฒˆ์—ญ ์˜ค๋ฅ˜: {str(e)}")
390
  return query
391
 
 
 
392
  def translate_to_korean(text):
393
  try:
394
  url = "https://translate.googleapis.com/translate_a/single"
@@ -400,7 +408,11 @@ def translate_to_korean(text):
400
  "q": text
401
  }
402
 
403
- response = requests.get(url, params=params)
 
 
 
 
404
  translated_text = response.json()[0][0][0]
405
  return translated_text
406
  except Exception as e:
@@ -421,8 +433,6 @@ def search_serphouse(query, country, page=1, num_result=10):
421
  date_range = f"{yesterday.strftime('%Y-%m-%d')},{now.strftime('%Y-%m-%d')}"
422
 
423
  translated_query = translate_query(query, country)
424
- print(f"Original query: {query}")
425
- print(f"Translated query: {translated_query}")
426
 
427
  payload = {
428
  "data": {
@@ -446,14 +456,48 @@ def search_serphouse(query, country, page=1, num_result=10):
446
  }
447
 
448
  try:
449
- response = requests.post(url, json=payload, headers=headers)
450
- print("Request payload:", json.dumps(payload, indent=2, ensure_ascii=False))
451
- print("Response status:", response.status_code)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
452
 
453
  response.raise_for_status()
454
  return {"results": response.json(), "translated_query": translated_query}
455
- except requests.RequestException as e:
456
- return {"error": f"Error: {str(e)}", "translated_query": query}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
457
 
458
  def format_results_from_raw(response_data):
459
  if "error" in response_data:
@@ -467,19 +511,35 @@ def format_results_from_raw(response_data):
467
  if not news_results:
468
  return "๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.", []
469
 
470
- articles = []
 
 
 
 
 
 
471
  for idx, result in enumerate(news_results, 1):
472
- articles.append({
473
- "index": idx,
474
- "title": result.get("title", "์ œ๋ชฉ ์—†์Œ"),
475
- "link": result.get("url", result.get("link", "#")),
476
- "snippet": result.get("snippet", "๋‚ด์šฉ ์—†์Œ"),
477
- "channel": result.get("channel", result.get("source", "์•Œ ์ˆ˜ ์—†์Œ")),
478
- "time": result.get("time", result.get("date", "์•Œ ์ˆ˜ ์—†๋Š” ์‹œ๊ฐ„")),
479
- "image_url": result.get("img", result.get("thumbnail", "")),
480
- "translated_query": translated_query
481
- })
482
- return "", articles
 
 
 
 
 
 
 
 
 
 
483
  except Exception as e:
484
  return f"๊ฒฐ๊ณผ ์ฒ˜๋ฆฌ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}", []
485
 
@@ -488,338 +548,174 @@ def serphouse_search(query, country):
488
  return format_results_from_raw(response_data)
489
 
490
 
491
-
492
-
493
-
494
- # Hacker News API ๊ด€๋ จ ํ•จ์ˆ˜๋“ค ๋จผ์ € ์ถ”๊ฐ€
495
- def get_hn_item(item_id):
496
- """๊ฐœ๋ณ„ ์•„์ดํ…œ ์ •๋ณด ๊ฐ€์ ธ์˜ค๊ธฐ"""
497
- try:
498
- response = requests.get(f"https://hacker-news.firebaseio.com/v0/item/{item_id}.json")
499
- return response.json()
500
- except:
501
- return None
502
-
503
- def get_recent_stories():
504
- """์ตœ์‹  ์Šคํ† ๋ฆฌ ๊ฐ€์ ธ์˜ค๊ธฐ"""
505
- try:
506
- response = requests.get("https://hacker-news.firebaseio.com/v0/newstories.json")
507
- story_ids = response.json()
508
-
509
- recent_stories = []
510
- current_time = datetime.now().timestamp()
511
- day_ago = current_time - (24 * 60 * 60)
512
-
513
- for story_id in story_ids:
514
- story = get_hn_item(story_id)
515
- if story and 'time' in story and story['time'] > day_ago:
516
- recent_stories.append(story)
517
-
518
- if len(recent_stories) >= 100:
519
- break
520
-
521
- return recent_stories
522
- except Exception as e:
523
- print(f"Error fetching HN stories: {str(e)}")
524
- return []
525
-
526
- def format_hn_time(timestamp):
527
- """Unix timestamp๋ฅผ ์ฝ๊ธฐ ์‰ฌ์šด ํ˜•์‹์œผ๋กœ ๋ณ€ํ™˜"""
528
- try:
529
- dt = datetime.fromtimestamp(timestamp)
530
- return dt.strftime("%Y-%m-%d %H:%M:%S")
531
- except:
532
- return "Unknown time"
533
-
534
-
535
- def clean_text(text):
536
- """HTML ํƒœ๊ทธ ์ œ๊ฑฐ ๋ฐ ํ…์ŠคํŠธ ์ •๋ฆฌ"""
537
- text = re.sub(r'\s+', ' ', text)
538
- text = re.sub(r'<[^>]+>', '', text)
539
- return text.strip()
540
-
541
- def get_article_content(url):
542
- """URL์—์„œ ๊ธฐ์‚ฌ ๋‚ด์šฉ ์Šคํฌ๋ž˜ํ•‘"""
543
- if not url:
544
- return None
545
-
546
- # ์Šคํ‚ตํ•  ๋„๋ฉ”์ธ ๋ชฉ๋ก
547
- skip_domains = ['github.com', 'twitter.com', 'linkedin.com', 'facebook.com']
548
- if any(domain in url.lower() for domain in skip_domains):
549
- return None
550
-
551
- try:
552
- headers = {
553
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
554
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
555
- 'Accept-Language': 'en-US,en;q=0.5',
556
- 'Connection': 'keep-alive',
557
- }
558
-
559
- # ํƒ€์ž„์•„์›ƒ ์ฆ๊ฐ€ ๋ฐ ์žฌ์‹œ๋„ ์„ค์ •
560
- session = requests.Session()
561
- retries = requests.adapters.Retry(total=3, backoff_factor=1)
562
- session.mount('https://', requests.adapters.HTTPAdapter(max_retries=retries))
563
 
564
- response = session.get(url, headers=headers, timeout=15)
565
- response.raise_for_status()
566
 
567
- soup = BeautifulSoup(response.text, 'html.parser')
 
568
 
569
- # ๋ถˆํ•„์š”ํ•œ ์š”์†Œ ์ œ๊ฑฐ
570
- for tag in soup(['script', 'style', 'nav', 'footer', 'header', 'aside', 'iframe']):
571
- tag.decompose()
572
-
573
- # ๋ณธ๋ฌธ ๋‚ด์šฉ ์ถ”์ถœ
574
- article_text = ""
575
 
576
- # article ํƒœ๊ทธ ํ™•์ธ
577
- article = soup.find('article')
578
- if article:
579
- paragraphs = article.find_all('p')
 
 
 
 
580
  else:
581
- # main ํƒœ๊ทธ ํ™•์ธ
582
- main = soup.find('main')
583
- if main:
584
- paragraphs = main.find_all('p')
585
- else:
586
- # body์—์„œ ์ง์ ‘ ๊ฒ€์ƒ‰
587
- paragraphs = soup.find_all('p')
588
-
589
- text = ' '.join(p.get_text().strip() for p in paragraphs if p.get_text().strip())
590
- text = clean_text(text)
591
-
592
- if not text:
593
- return None
594
-
595
- return text[:4000] # ํ…์ŠคํŠธ ๊ธธ์ด ์ œํ•œ
596
-
597
- except Exception as e:
598
- print(f"Scraping error for {url}: {str(e)}")
599
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
600
 
601
- def generate_summary(text):
602
- """CohereForAI ๋ชจ๋ธ์„ ์‚ฌ์šฉํ•œ ์š”์•ฝ ์ƒ์„ฑ"""
603
- if not text:
604
- return None
605
 
606
- prompt = """๋ฐ˜๋“œ์‹œ ํ•œ๊ธ€(ํ•œ๊ตญ์–ด)๋กœ ์ž‘์„ฑํ•˜๋ผ. Please analyze and summarize the following text in 2-3 sentences.
607
- Focus on the main points and key information:
608
 
609
- Text: {text}
610
-
611
- Summary:"""
612
-
613
- try:
614
- response = hf_client.text_generation(
615
- prompt.format(text=text),
616
- max_new_tokens=500,
617
- temperature=0.5,
618
- repetition_penalty=1.2
619
- )
620
- return response
621
- except Exception as e:
622
- print(f"Summary generation error: {str(e)}")
623
- return None
624
 
625
- def process_hn_story(story, progress=None):
626
- """๊ฐœ๋ณ„ ์Šคํ† ๋ฆฌ ์ฒ˜๋ฆฌ ๋ฐ ์š”์•ฝ"""
627
- try:
628
- url = story.get('url')
629
- if not url:
630
- return None # ์Šคํ‚ตํ•  ์Šคํ† ๋ฆฌ
631
-
632
- content = get_article_content(url)
633
- if not content:
634
- return None # ์Šคํฌ๋ž˜ํ•‘ ์‹คํŒจํ•œ ์Šคํ† ๋ฆฌ ์Šคํ‚ต
635
-
636
- summary_en = generate_summary(content)
637
- if not summary_en:
638
- return None # ์š”์•ฝ ์‹คํŒจํ•œ ์Šคํ† ๋ฆฌ ์Šคํ‚ต
639
-
640
- summary_ko = translate_to_korean(summary_en)
641
- if not summary_ko:
642
- return None # ๋ฒˆ์—ญ ์‹คํŒจํ•œ ์Šคํ† ๋ฆฌ ์Šคํ‚ต
643
-
644
- return {
645
- 'story': story,
646
- 'summary': summary_ko
647
- }
648
-
649
- except Exception as e:
650
- print(f"Story processing error: {str(e)}")
651
- return None # ์—๋Ÿฌ ๋ฐœ์ƒํ•œ ์Šคํ† ๋ฆฌ ์Šคํ‚ต
652
 
653
- def refresh_hn_stories():
654
- """Hacker News ์Šคํ† ๋ฆฌ ์ƒˆ๋กœ๊ณ ์นจ (์‹ค์‹œ๊ฐ„ ์ถœ๋ ฅ ๋ฒ„์ „)"""
655
- status_msg = "Hacker News ํฌ์ŠคํŠธ๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ์ค‘..."
656
- outputs = [gr.update(value=status_msg, visible=True)]
657
 
658
- # ์ปดํฌ๋„ŒํŠธ ์ดˆ๊ธฐํ™”
659
- for comp in hn_article_components:
660
  outputs.extend([
661
- gr.update(visible=False),
662
- gr.update(),
663
- gr.update(),
664
- gr.update(visible=False), # report_button
665
- gr.update(visible=False), # report_content
666
- gr.update(visible=False) # show_report
667
  ])
668
-
 
669
  yield outputs
670
 
671
- # ์ตœ์‹  ์Šคํ† ๋ฆฌ ๊ฐ€์ ธ์˜ค๊ธฐ
672
- stories = get_recent_stories()
673
- processed_count = 0
674
- valid_stories = [] # ์„ฑ๊ณต์ ์œผ๋กœ ์ฒ˜๋ฆฌ๋œ ์Šคํ† ๋ฆฌ ์ €์žฅ
675
-
676
- with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
677
- future_to_story = {executor.submit(process_hn_story, story): story
678
- for story in stories[:100]}
679
-
680
- for future in concurrent.futures.as_completed(future_to_story):
681
- processed_count += 1
682
- result = future.result()
683
 
684
- if result: # ์„ฑ๊ณต์ ์œผ๋กœ ์ฒ˜๋ฆฌ๋œ ์Šคํ† ๋ฆฌ๋งŒ ์ถ”๊ฐ€
685
- valid_stories.append((result['story'], result['summary']))
 
 
 
686
 
687
- # ํ˜„์žฌ๊นŒ์ง€์˜ ๊ฒฐ๊ณผ ์ถœ๋ ฅ
688
- outputs = [gr.update(value=f"์ฒ˜๋ฆฌ ์ค‘... ({len(valid_stories)}/{processed_count} ์„ฑ๊ณต)", visible=True)]
689
 
690
- # ๋ชจ๋“  ์ปดํฌ๋„ŒํŠธ ์—…๋ฐ์ดํŠธ
691
- for idx, comp in enumerate(hn_article_components):
692
- if idx < len(valid_stories):
693
- story, summary = valid_stories[idx]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
694
  outputs.extend([
695
  gr.update(visible=True),
696
- gr.update(value=f"### [{story.get('title', 'Untitled')}]({story.get('url', '#')})"),
697
- gr.update(value=f"""
698
- **์ž‘์„ฑ์ž:** {story.get('by', 'unknown')} |
699
- **์‹œ๊ฐ„:** {format_hn_time(story.get('time', 0))} |
700
- **์ ์ˆ˜:** {story.get('score', 0)} |
701
- **๋Œ“๊ธ€:** {len(story.get('kids', []))}๊ฐœ\n
702
- **AI ์š”์•ฝ:** {summary}
703
- """),
704
- gr.update(visible=True), # report_button
705
- gr.update(visible=False), # report_content
706
- gr.update(visible=False) # show_report
707
  ])
708
  else:
709
  outputs.extend([
710
  gr.update(visible=False),
711
  gr.update(),
712
  gr.update(),
713
- gr.update(visible=False),
714
- gr.update(visible=False),
715
- gr.update(visible=False)
716
  ])
717
-
718
- yield outputs
719
-
720
- # ์ตœ์ข… ์ƒํƒœ ์—…๋ฐ์ดํŠธ
721
- final_outputs = [gr.update(value=f"์ด {len(valid_stories)}๊ฐœ์˜ ํฌ์ŠคํŠธ๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ์ฒ˜๋ฆฌ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. (์ „์ฒด ์‹œ๋„: {processed_count})", visible=True)]
722
-
723
- for idx, comp in enumerate(hn_article_components):
724
- if idx < len(valid_stories):
725
- story, summary = valid_stories[idx]
726
- final_outputs.extend([
727
- gr.update(visible=True),
728
- gr.update(value=f"### [{story.get('title', 'Untitled')}]({story.get('url', '#')})"),
729
- gr.update(value=f"""
730
- **์ž‘์„ฑ์ž:** {story.get('by', 'unknown')} |
731
- **์‹œ๊ฐ„:** {format_hn_time(story.get('time', 0))} |
732
- **์ ์ˆ˜:** {story.get('score', 0)} |
733
- **๋Œ“๊ธ€:** {len(story.get('kids', []))}๊ฐœ\n
734
- **AI ์š”์•ฝ:** {summary}
735
- """),
736
- gr.update(visible=True), # report_button
737
- gr.update(visible=False), # report_content
738
- gr.update(visible=False) # show_report
739
- ])
740
- else:
741
- final_outputs.extend([
742
- gr.update(visible=False),
743
- gr.update(),
744
- gr.update(),
745
- gr.update(visible=False),
746
- gr.update(visible=False),
747
- gr.update(visible=False)
748
- ])
749
-
750
- yield final_outputs
751
-
752
- def generate_report(title, info, progress=gr.Progress()):
753
- """๋ฆฌํฌํŒ… ์ƒ์„ฑ"""
754
- try:
755
- progress(0.1, desc="๋ฆฌํฌํŒ… ์ƒ์„ฑ ์ค€๋น„ ์ค‘...")
756
-
757
- # HTML ํƒœ๊ทธ ์ œ๊ฑฐ ๋ฐ ํ…์ŠคํŠธ ์ถ”์ถœ
758
- title_text = re.sub(r'#*\s*\[(.*?)\].*', r'\1', title)
759
- info_text = re.sub(r'\*\*(.*?)\*\*|\n|AI ์š”์•ฝ:|์ž‘์„ฑ์ž:|์‹œ๊ฐ„:|์ ์ˆ˜:|๋Œ“๊ธ€:', ' ', info)
760
- info_text = ' '.join(info_text.split())
761
-
762
- progress(0.3, desc="ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ ์ค‘...")
763
-
764
- prompt = f"""๋„ˆ๋Š” Hacker News ํฌ์ŠคํŠธ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋ณด๋„ ๊ธฐ์‚ฌ ํ˜•ํƒœ์˜ ๋ฆฌํฌํŒ…์„ ์ž‘์„ฑํ•˜๋Š” ์—ญํ• ์ด๋‹ค.
765
- ๋„ˆ๋Š” ๋ฐ˜๋“œ์‹œ ํ•œ๊ธ€๋กœ ๋ฆฌํฌํŒ… ํ˜•์‹์˜ ๊ฐ๊ด€์  ๊ธฐ์‚ฌ ํ˜•ํƒœ๋กœ ์ž‘์„ฑํ•˜์—ฌ์•ผ ํ•œ๋‹ค.
766
- ์ƒ์„ฑ์‹œ 6ํ•˜์›์น™์— ์ž…๊ฐํ•˜๊ณ  ๊ธธ์ด๋Š” 4000ํ† ํฐ์„ ๋„˜์ง€ ์•Š์„๊ฒƒ.
767
- ๋„ˆ์˜ ์ถœ์ฒ˜๋‚˜ ๋ชจ๋ธ, ์ง€์‹œ๋ฌธ ๋“ฑ์„ ๋…ธ์ถœํ•˜์ง€ ๋ง๊ฒƒ
768
-
769
- ์ œ๋ชฉ: {title_text}
770
- ๋‚ด์šฉ: {info_text}
771
- """
772
-
773
- progress(0.5, desc="AI ๋ชจ๋ธ ์ฒ˜๋ฆฌ ์ค‘...")
774
-
775
- try:
776
- response = hf_client.text_generation(
777
- prompt,
778
- max_new_tokens=2000,
779
- temperature=0.7,
780
- repetition_penalty=1.2,
781
- return_full_text=False
782
- )
783
-
784
- progress(1.0, desc="์™„๋ฃŒ!")
785
-
786
- if response:
787
- formatted_response = f"### AI ๋ฆฌํฌํŒ…\n\n{response}"
788
- return [
789
- gr.update(value=formatted_response, visible=True), # report_content
790
- gr.update(value="์ ‘๊ธฐ", visible=True) # show_report
791
- ]
792
 
 
 
 
793
  except Exception as e:
794
- print(f"Model error: {str(e)}")
795
- time.sleep(2) # ์ž ์‹œ ๋Œ€๊ธฐ
796
-
797
- return [
798
- gr.update(value="๋ฆฌํฌํŒ… ์ƒ์„ฑ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์‹œ๋„ํ•ด์ฃผ์„ธ์š”.", visible=True),
799
- gr.update(value="์ ‘๊ธฐ", visible=True)
800
- ]
801
-
802
- except Exception as e:
803
- print(f"Report generation error: {str(e)}")
804
- return [
805
- gr.update(value="๋ฆฌํฌํŒ… ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.", visible=True),
806
- gr.update(value="์ ‘๊ธฐ", visible=True)
807
- ]
808
-
809
- def toggle_report(report_content, show_report):
810
- """๋ฆฌํฌํŠธ ํ‘œ์‹œ/์ˆจ๊น€ ํ† ๊ธ€"""
811
- try:
812
- is_visible = report_content.visible
813
- return [
814
- gr.update(visible=not is_visible), # report_content
815
- gr.update(value="์ ‘๊ธฐ" if not is_visible else "ํŽผ์ณ ๋ณด๊ธฐ") # show_report
816
- ]
817
- except AttributeError:
818
- # report_content๊ฐ€ ๋ฌธ์ž์—ด์ธ ๊ฒฝ์šฐ
819
- return [
820
- gr.update(visible=True), # report_content
821
- gr.update(value="์ ‘๊ธฐ") # show_report
822
- ]
823
 
824
  css = """
825
  /* ์ „์—ญ ์Šคํƒ€์ผ */
@@ -888,260 +784,236 @@ footer {visibility: hidden;}
888
  border-radius: 4px !important;
889
  }
890
 
891
- /* Hacker News ์•„ํ‹ฐํด ์Šคํƒ€์ผ */
892
- .hn-article-group {
893
- height: auto !important;
894
- min-height: 250px;
895
- margin-bottom: 20px;
896
- padding: 15px;
897
- border: 1px solid #eee;
898
- border-radius: 5px;
899
- background: white;
900
- box-shadow: 0 1px 3px rgba(0,0,0,0.05);
901
- }
902
-
903
- /* ๋ฆฌํฌํŠธ ์„น์…˜ ์Šคํƒ€์ผ */
904
- .report-section {
905
- margin-top: 15px;
906
- padding: 15px;
907
- border-top: 1px solid #eee;
908
- background: #f9f9f9;
909
- border-radius: 4px;
910
- }
911
-
912
- .report-content {
913
- margin-top: 15px;
914
- padding: 15px;
915
- border-top: 1px solid #eee;
916
- background: #f9f9f9;
917
- border-radius: 4px;
918
- font-size: 0.95em;
919
- line-height: 1.6;
920
- }
921
-
922
- /* ํ”„๋กœ๊ทธ๋ ˆ์Šค ๋ฐ” */
923
- .progress {
924
  position: fixed;
925
  top: 0;
926
  left: 0;
927
  width: 100%;
928
- height: 4px;
929
- background: #f0f0f0;
930
  z-index: 1000;
931
  }
932
 
 
933
  .progress-bar {
934
  height: 100%;
935
- background: #1f77b4;
 
936
  transition: width 0.3s ease;
937
- position: fixed;
938
- top: 0;
939
- left: 0;
940
- width: 100%;
941
- z-index: 1000;
942
  }
943
 
944
- /* ๋ฆฌํฌํŠธ ์ฝ˜ํ…์ธ  ํ† ๊ธ€ */
945
- .hn-article-group .report-content {
946
- display: none;
947
- margin-top: 15px;
948
- padding: 15px;
949
- border-top: 1px solid #eee;
950
- background: #f9f9f9;
951
- transition: all 0.3s ease;
 
 
 
 
 
952
  }
953
 
954
- .hn-article-group .report-content.visible {
955
- display: block;
 
 
 
 
 
 
 
 
 
956
  }
957
 
958
  /* ๋ฐ˜์‘ํ˜• ๋””์ž์ธ */
959
  @media (max-width: 768px) {
960
- .hn-article-group {
961
  padding: 10px;
962
  margin-bottom: 15px;
963
  }
964
 
965
- .report-content {
966
- padding: 10px;
 
967
  }
968
  }
969
- """
970
 
 
 
 
 
 
 
971
 
 
 
 
 
 
 
972
 
973
-
974
-
975
- # ๊ธฐ์กด ํ•จ์ˆ˜๋“ค
976
- def search_and_display(query, country, articles_state, progress=gr.Progress()):
977
- status_msg = "๊ฒ€์ƒ‰์„ ์ง„ํ–‰์ค‘์ž…๋‹ˆ๋‹ค. ์ž ์‹œ๋งŒ ๊ธฐ๋‹ค๋ฆฌ์„ธ์š”..."
978
-
979
- progress(0, desc="๊ฒ€์ƒ‰์–ด ๋ฒˆ์—ญ ์ค‘...")
980
- translated_query = translate_query(query, country)
981
- translated_display = f"**์›๋ณธ ๊ฒ€์ƒ‰์–ด:** {query}\n**๋ฒˆ์—ญ๋œ ๊ฒ€์ƒ‰์–ด:** {translated_query}" if translated_query != query else f"**๊ฒ€์ƒ‰์–ด:** {query}"
982
-
983
- progress(0.2, desc="๊ฒ€์ƒ‰ ์‹œ์ž‘...")
984
- error_message, articles = serphouse_search(query, country)
985
- progress(0.5, desc="๊ฒฐ๊ณผ ์ฒ˜๋ฆฌ ์ค‘...")
986
-
987
- outputs = []
988
- outputs.append(gr.update(value=status_msg, visible=True))
989
- outputs.append(gr.update(value=translated_display, visible=True))
990
-
991
- if error_message:
992
- outputs.append(gr.update(value=error_message, visible=True))
993
- for comp in article_components:
994
- outputs.extend([
995
- gr.update(visible=False), gr.update(), gr.update(),
996
- gr.update(), gr.update()
997
- ])
998
- articles_state = []
999
- else:
1000
- outputs.append(gr.update(value="", visible=False))
1001
- total_articles = len(articles)
1002
- for idx, comp in enumerate(article_components):
1003
- progress((idx + 1) / total_articles, desc=f"๊ฒฐ๊ณผ ํ‘œ์‹œ ์ค‘... {idx + 1}/{total_articles}")
1004
- if idx < len(articles):
1005
- article = articles[idx]
1006
- image_url = article['image_url']
1007
- image_update = gr.update(value=image_url, visible=True) if image_url and not image_url.startswith('data:image') else gr.update(value=None, visible=False)
1008
-
1009
- korean_summary = translate_to_korean(article['snippet'])
1010
-
1011
- outputs.extend([
1012
- gr.update(visible=True),
1013
- gr.update(value=f"### [{article['title']}]({article['link']})"),
1014
- image_update,
1015
- gr.update(value=f"**์š”์•ฝ:** {article['snippet']}\n\n**ํ•œ๊ธ€ ์š”์•ฝ:** {korean_summary}"),
1016
- gr.update(value=f"**์ถœ์ฒ˜:** {article['channel']} | **์‹œ๊ฐ„:** {article['time']}")
1017
- ])
1018
- else:
1019
- outputs.extend([
1020
- gr.update(visible=False), gr.update(), gr.update(),
1021
- gr.update(), gr.update()
1022
- ])
1023
- articles_state = articles
1024
 
1025
- progress(1.0, desc="์™„๋ฃŒ!")
1026
- outputs.append(articles_state)
1027
- outputs[0] = gr.update(value="", visible=False)
1028
-
1029
- return outputs
1030
 
 
 
 
 
 
 
 
 
1031
 
1032
- def get_region_countries(region):
1033
- """์„ ํƒ๋œ ์ง€์—ญ์˜ ๊ตญ๊ฐ€ ๋ฐ ์–ธ์–ด ์ •๋ณด ๋ฐ˜ํ™˜"""
1034
- if region == "๋™์•„์‹œ์•„":
1035
- return COUNTRY_LOCATIONS_EAST_ASIA, COUNTRY_LANGUAGES_EAST_ASIA
1036
- elif region == "๋™๋‚จ์•„์‹œ์•„/์˜ค์„ธ์•„๋‹ˆ์•„":
1037
- return COUNTRY_LOCATIONS_SOUTHEAST_ASIA_OCEANIA, COUNTRY_LANGUAGES_SOUTHEAST_ASIA_OCEANIA
1038
- elif region == "๋™์œ ๋Ÿฝ":
1039
- return COUNTRY_LOCATIONS_EAST_EUROPE, COUNTRY_LANGUAGES_EAST_EUROPE
1040
- elif region == "์„œ์œ ๋Ÿฝ":
1041
- return COUNTRY_LOCATIONS_WEST_EUROPE, COUNTRY_LANGUAGES_WEST_EUROPE
1042
- elif region == "์ค‘๋™/์•„ํ”„๋ฆฌ์นด":
1043
- return COUNTRY_LOCATIONS_ARAB_AFRICA, COUNTRY_LANGUAGES_ARAB_AFRICA
1044
- elif region == "์•„๋ฉ”๋ฆฌ์นด":
1045
- return COUNTRY_LOCATIONS_AMERICA, COUNTRY_LANGUAGES_AMERICA
1046
- return {}, {}
1047
 
1048
- def search_global(query, region, articles_state_global):
1049
- """์ง€์—ญ๋ณ„ ๊ฒ€์ƒ‰ ํ•จ์ˆ˜"""
1050
- status_msg = f"{region} ์ง€์—ญ ๊ฒ€์ƒ‰์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค..."
1051
- all_results = []
 
 
1052
 
1053
- outputs = [
1054
- gr.update(value=status_msg, visible=True),
1055
- gr.update(value=f"**๊ฒ€์ƒ‰์–ด:** {query}", visible=True),
1056
- ]
1057
-
1058
- for _ in global_article_components:
1059
- outputs.extend([
1060
- gr.update(visible=False), gr.update(), gr.update(),
1061
- gr.update(), gr.update()
1062
- ])
1063
- outputs.append([])
1064
-
1065
- yield outputs
1066
-
1067
- # ์„ ํƒ๋œ ์ง€์—ญ์˜ ๊ตญ๊ฐ€ ์ •๋ณด ๊ฐ€์ ธ์˜ค๊ธฐ
1068
- locations, languages = get_region_countries(region)
1069
- total_countries = len(locations)
1070
 
1071
- for idx, (country, location) in enumerate(locations.items(), 1):
1072
- try:
1073
- status_msg = f"{region} - {country} ๊ฒ€์ƒ‰ ์ค‘... ({idx}/{total_countries} ๊ตญ๊ฐ€)"
1074
- outputs[0] = gr.update(value=status_msg, visible=True)
1075
- yield outputs
1076
-
1077
- error_message, articles = serphouse_search(query, country)
1078
- if not error_message and articles:
1079
- for article in articles:
1080
- article['source_country'] = country
1081
- article['region'] = region
1082
-
1083
- all_results.extend(articles)
1084
- sorted_results = sorted(all_results, key=lambda x: x.get('time', ''), reverse=True)
1085
-
1086
- seen_urls = set()
1087
- unique_results = []
1088
- for article in sorted_results:
1089
- url = article.get('link', '')
1090
- if url not in seen_urls:
1091
- seen_urls.add(url)
1092
- unique_results.append(article)
1093
-
1094
- unique_results = unique_results[:MAX_GLOBAL_RESULTS]
1095
-
1096
- outputs = [
1097
- gr.update(value=f"{region} - {idx}/{total_countries} ๊ตญ๊ฐ€ ๊ฒ€์ƒ‰ ์™„๋ฃŒ\nํ˜„์žฌ๊นŒ์ง€ ๋ฐœ๊ฒฌ๋œ ๋‰ด์Šค: {len(unique_results)}๊ฑด", visible=True),
1098
- gr.update(value=f"**๊ฒ€์ƒ‰์–ด:** {query} | **์ง€์—ญ:** {region}", visible=True),
1099
- ]
1100
-
1101
- for idx, comp in enumerate(global_article_components):
1102
- if idx < len(unique_results):
1103
- article = unique_results[idx]
1104
- image_url = article.get('image_url', '')
1105
- image_update = gr.update(value=image_url, visible=True) if image_url and not image_url.startswith('data:image') else gr.update(value=None, visible=False)
1106
-
1107
- korean_summary = translate_to_korean(article['snippet'])
1108
-
1109
- outputs.extend([
1110
- gr.update(visible=True),
1111
- gr.update(value=f"### [{article['title']}]({article['link']})"),
1112
- image_update,
1113
- gr.update(value=f"**์š”์•ฝ:** {article['snippet']}\n\n**ํ•œ๊ธ€ ์š”์•ฝ:** {korean_summary}"),
1114
- gr.update(value=f"**์ถœ์ฒ˜:** {article['channel']} | **๊ตญ๊ฐ€:** {article['source_country']} | **์ง€์—ญ:** {article['region']} | **์‹œ๊ฐ„:** {article['time']}")
1115
- ])
1116
- else:
1117
- outputs.extend([
1118
- gr.update(visible=False),
1119
- gr.update(),
1120
- gr.update(),
1121
- gr.update(),
1122
- gr.update()
1123
- ])
1124
 
1125
- outputs.append(unique_results)
1126
- yield outputs
1127
-
1128
- except Exception as e:
1129
- print(f"Error searching {country}: {str(e)}")
1130
- continue
1131
-
1132
- final_status = f"{region} ๊ฒ€์ƒ‰ ์™„๋ฃŒ! ์ด {len(unique_results)}๊ฐœ์˜ ๋‰ด์Šค๊ฐ€ ๋ฐœ๊ฒฌ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."
1133
- outputs[0] = gr.update(value=final_status, visible=True)
1134
- yield outputs
1135
-
 
 
 
 
 
 
 
 
1136
 
1137
-
1138
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1139
 
 
 
 
 
 
 
 
 
 
 
 
1140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1141
 
 
 
 
 
1142
 
 
1143
 
1144
- with gr.Blocks(theme="Nymbo/Nymbo_Theme", css=css, title="NewsAI ์„œ๋น„์Šค") as iface:
1145
  with gr.Tabs():
1146
  # ๊ตญ๊ฐ€๋ณ„ ํƒญ
1147
  with gr.Tab("๊ตญ๊ฐ€๋ณ„"):
@@ -1157,9 +1029,35 @@ with gr.Blocks(theme="Nymbo/Nymbo_Theme", css=css, title="NewsAI ์„œ๋น„์Šค") as
1157
  value="United States"
1158
  )
1159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1160
  status_message = gr.Markdown("", visible=True)
1161
  translated_query_display = gr.Markdown(visible=False)
1162
  search_button = gr.Button("๊ฒ€์ƒ‰", variant="primary")
 
1163
 
1164
  progress = gr.Progress()
1165
  articles_state = gr.State([])
@@ -1218,36 +1116,87 @@ with gr.Blocks(theme="Nymbo/Nymbo_Theme", css=css, title="NewsAI ์„œ๋น„์Šค") as
1218
  'index': i,
1219
  })
1220
 
1221
- # AI ๋ฆฌํฌํ„ฐ ํƒญ
1222
- with gr.Tab("AI ๋ฆฌํฌํ„ฐ"):
1223
- gr.Markdown("์ง€๋‚œ 24์‹œ๊ฐ„ ๋™์•ˆ์˜ Hacker News ํฌ์ŠคํŠธ๋ฅผ AI๊ฐ€ ์š”์•ฝํ•˜์—ฌ ๋ณด์—ฌ์ค๋‹ˆ๋‹ค.")
1224
-
 
1225
  with gr.Column():
1226
- refresh_button = gr.Button("์ƒˆ๋กœ๊ณ ์นจ", variant="primary")
1227
- status_message_hn = gr.Markdown("")
1228
-
1229
- with gr.Column(elem_id="hn_results_area"):
1230
- hn_articles_state = gr.State([])
1231
- hn_article_components = []
1232
- for i in range(100):
1233
- with gr.Group(visible=False, elem_classes="hn-article-group") as article_group:
1234
- title = gr.Markdown()
1235
- info = gr.Markdown()
1236
- with gr.Row():
1237
- report_button = gr.Button("๋ฆฌํฌํŒ… ์ƒ์„ฑ", size="sm", variant="primary")
1238
- show_report = gr.Button("ํŽผ์ณ ๋ณด๊ธฐ", size="sm", visible=False)
1239
- report_content = gr.Markdown(visible=False)
1240
-
1241
- hn_article_components.append({
1242
- 'group': article_group,
1243
- 'title': title,
1244
- 'info': info,
1245
- 'report_button': report_button,
1246
- 'show_report': show_report,
1247
- 'report_content': report_content,
1248
- 'index': i,
1249
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1250
 
 
 
1251
  # ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ ๋ถ€๋ถ„
1252
  # ๊ตญ๊ฐ€๋ณ„ ํƒญ ์ด๋ฒคํŠธ
1253
  search_outputs = [status_message, translated_query_display, gr.Markdown(visible=False)]
@@ -1281,61 +1230,11 @@ with gr.Blocks(theme="Nymbo/Nymbo_Theme", css=css, title="NewsAI ์„œ๋น„์Šค") as
1281
  show_progress=True
1282
  )
1283
 
1284
- # AI ๋ฆฌํฌํ„ฐ ํƒญ ์ด๋ฒคํŠธ
1285
- hn_outputs = [status_message_hn]
1286
- for comp in hn_article_components:
1287
- hn_outputs.extend([
1288
- comp['group'],
1289
- comp['title'],
1290
- comp['info'],
1291
- comp['report_button'],
1292
- comp['report_content'],
1293
- comp['show_report']
1294
- ])
1295
-
1296
- # ๊ฐ ์ปดํฌ๋„ŒํŠธ๋ณ„ ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ
1297
- for comp in hn_article_components:
1298
- # ๋ฆฌํฌํŒ… ์ƒ์„ฑ ๋ฒ„ํŠผ ์ด๋ฒคํŠธ
1299
- comp['report_button'].click(
1300
- fn=generate_report,
1301
- inputs=[
1302
- comp['title'],
1303
- comp['info']
1304
- ],
1305
- outputs=[
1306
- comp['report_content'],
1307
- comp['show_report']
1308
- ],
1309
- api_name=f"generate_report_{comp['index']}",
1310
- show_progress=True
1311
- )
1312
-
1313
- # ํŽผ์ณ๋ณด๊ธฐ/์ ‘๊ธฐ ๋ฒ„ํŠผ ์ด๋ฒคํŠธ
1314
- comp['show_report'].click(
1315
- fn=toggle_report,
1316
- inputs=[
1317
- comp['report_content'],
1318
- comp['show_report']
1319
- ],
1320
- outputs=[
1321
- comp['report_content'],
1322
- comp['show_report']
1323
- ],
1324
- api_name=f"toggle_report_{comp['index']}"
1325
- )
1326
-
1327
- # ์ƒˆ๋กœ๊ณ ์นจ ๋ฒ„ํŠผ ์ด๋ฒคํŠธ
1328
- refresh_button.click(
1329
- fn=refresh_hn_stories,
1330
- outputs=hn_outputs,
1331
- show_progress=True
1332
- )
1333
-
1334
  iface.launch(
1335
  server_name="0.0.0.0",
1336
  server_port=7860,
1337
  share=True,
1338
- auth=("it1","chosun1"),
1339
  ssl_verify=False,
1340
  show_error=True
1341
- )
 
3
  import json
4
  import os
5
  from datetime import datetime, timedelta
6
+ from concurrent.futures import ThreadPoolExecutor
7
+ from functools import lru_cache
8
+ from requests.adapters import HTTPAdapter
9
+ from requests.packages.urllib3.util.retry import Retry
10
+ from openai import OpenAI
11
  from bs4 import BeautifulSoup
12
+
13
+ ACCESS_TOKEN = os.getenv("HF_TOKEN")
14
+ if not ACCESS_TOKEN:
15
+ raise ValueError("HF_TOKEN environment variable is not set")
16
+
17
+ client = OpenAI(
18
+ base_url="https://api-inference.huggingface.co/v1/",
19
+ api_key=ACCESS_TOKEN,
20
+ )
21
 
22
  MAX_COUNTRY_RESULTS = 100 # ๊ตญ๊ฐ€๋ณ„ ์ตœ๋Œ€ ๊ฒฐ๊ณผ ์ˆ˜
23
  MAX_GLOBAL_RESULTS = 1000 # ์ „์„ธ๊ณ„ ์ตœ๋Œ€ ๊ฒฐ๊ณผ ์ˆ˜
 
42
  return article_components
43
 
44
  API_KEY = os.getenv("SERPHOUSE_API_KEY")
 
45
 
46
  # ๊ตญ๊ฐ€๋ณ„ ์–ธ์–ด ์ฝ”๋“œ ๋งคํ•‘
47
  COUNTRY_LANGUAGES = {
48
  "United States": "en",
49
  "United Kingdom": "en",
50
+ "Taiwan": "zh-TW",
51
  "Canada": "en",
52
  "Australia": "en",
53
  "Germany": "de",
 
117
  COUNTRY_LOCATIONS = {
118
  "United States": "United States",
119
  "United Kingdom": "United Kingdom",
120
+ "Taiwan": "Taiwan",
121
  "Canada": "Canada",
122
  "Australia": "Australia",
123
  "Germany": "Germany",
 
184
  "Iceland": "Iceland"
185
  }
186
 
187
+ # ์ง€์—ญ ์ •์˜
 
188
  # ๋™์•„์‹œ์•„ ์ง€์—ญ
189
  COUNTRY_LANGUAGES_EAST_ASIA = {
190
  "Taiwan": "zh-TW",
 
359
  "์•„๋ฉ”๋ฆฌ์นด"
360
  ]
361
 
362
+
363
+ @lru_cache(maxsize=100)
364
  def translate_query(query, country):
365
  try:
 
366
  if is_english(query):
 
367
  return query
368
 
 
369
  if country in COUNTRY_LANGUAGES:
 
370
  if country == "South Korea":
 
371
  return query
372
 
373
  target_lang = COUNTRY_LANGUAGES[country]
 
374
 
375
+ url = "https://translate.googleapis.com/translate_a/single"
376
  params = {
377
  "client": "gtx",
378
  "sl": "auto",
 
381
  "q": query
382
  }
383
 
384
+ session = requests.Session()
385
+ retries = Retry(total=3, backoff_factor=0.5)
386
+ session.mount('https://', HTTPAdapter(max_retries=retries))
387
+
388
+ response = session.get(url, params=params, timeout=(5, 10))
389
  translated_text = response.json()[0][0][0]
 
390
  return translated_text
391
 
392
  return query
 
395
  print(f"๋ฒˆ์—ญ ์˜ค๋ฅ˜: {str(e)}")
396
  return query
397
 
398
+
399
+ @lru_cache(maxsize=200)
400
  def translate_to_korean(text):
401
  try:
402
  url = "https://translate.googleapis.com/translate_a/single"
 
408
  "q": text
409
  }
410
 
411
+ session = requests.Session()
412
+ retries = Retry(total=3, backoff_factor=0.5)
413
+ session.mount('https://', HTTPAdapter(max_retries=retries))
414
+
415
+ response = session.get(url, params=params, timeout=(5, 10))
416
  translated_text = response.json()[0][0][0]
417
  return translated_text
418
  except Exception as e:
 
433
  date_range = f"{yesterday.strftime('%Y-%m-%d')},{now.strftime('%Y-%m-%d')}"
434
 
435
  translated_query = translate_query(query, country)
 
 
436
 
437
  payload = {
438
  "data": {
 
456
  }
457
 
458
  try:
459
+ # ์„ธ์…˜ ์„ค์ • ๊ฐœ์„ 
460
+ session = requests.Session()
461
+
462
+ # ์žฌ์‹œ๋„ ์„ค์ • ๊ฐ•ํ™”
463
+ retries = Retry(
464
+ total=5, # ์ตœ๋Œ€ ์žฌ์‹œ๋„ ํšŸ์ˆ˜ ์ฆ๊ฐ€
465
+ backoff_factor=1, # ์žฌ์‹œ๋„ ๊ฐ„๊ฒฉ ์ฆ๊ฐ€
466
+ status_forcelist=[500, 502, 503, 504, 429], # ์žฌ์‹œ๋„ํ•  HTTP ์ƒํƒœ ์ฝ”๋“œ
467
+ allowed_methods=["POST"] # POST ์š”์ฒญ์— ๋Œ€ํ•œ ์žฌ์‹œ๋„ ํ—ˆ์šฉ
468
+ )
469
+
470
+ # ํƒ€์ž„์•„์›ƒ ์„ค์ • ์กฐ์ •
471
+ adapter = HTTPAdapter(max_retries=retries)
472
+ session.mount('http://', adapter)
473
+ session.mount('https://', adapter)
474
+
475
+ # ํƒ€์ž„์•„์›ƒ ๊ฐ’ ์ฆ๊ฐ€ (connect timeout, read timeout)
476
+ response = session.post(
477
+ url,
478
+ json=payload,
479
+ headers=headers,
480
+ timeout=(30, 30) # ์—ฐ๊ฒฐ ํƒ€์ž„์•„์›ƒ 30์ดˆ, ์ฝ๊ธฐ ํƒ€์ž„์•„์›ƒ 30์ดˆ
481
+ )
482
 
483
  response.raise_for_status()
484
  return {"results": response.json(), "translated_query": translated_query}
485
+
486
+ except requests.exceptions.Timeout:
487
+ return {
488
+ "error": "๊ฒ€์ƒ‰ ์‹œ๊ฐ„์ด ์ดˆ๊ณผ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์ž ์‹œ ํ›„ ๋‹ค์‹œ ์‹œ๋„ํ•ด์ฃผ์„ธ์š”.",
489
+ "translated_query": query
490
+ }
491
+ except requests.exceptions.RequestException as e:
492
+ return {
493
+ "error": f"๊ฒ€์ƒ‰ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}",
494
+ "translated_query": query
495
+ }
496
+ except Exception as e:
497
+ return {
498
+ "error": f"์˜ˆ๊ธฐ์น˜ ์•Š์€ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}",
499
+ "translated_query": query
500
+ }
501
 
502
  def format_results_from_raw(response_data):
503
  if "error" in response_data:
 
511
  if not news_results:
512
  return "๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.", []
513
 
514
+ # ํ•œ๊ตญ ๋„๋ฉ”์ธ ๋ฐ ํ•œ๊ตญ ๊ด€๋ จ ํ‚ค์›Œ๋“œ ํ•„ํ„ฐ๋ง
515
+ korean_domains = ['.kr', 'korea', 'korean', 'yonhap', 'hankyung', 'chosun',
516
+ 'donga', 'joins', 'hani', 'koreatimes', 'koreaherald']
517
+ korean_keywords = ['korea', 'korean', 'seoul', 'busan', 'incheon', 'daegu',
518
+ 'gwangju', 'daejeon', 'ulsan', 'sejong']
519
+
520
+ filtered_articles = []
521
  for idx, result in enumerate(news_results, 1):
522
+ url = result.get("url", result.get("link", "")).lower()
523
+ title = result.get("title", "").lower()
524
+ channel = result.get("channel", result.get("source", "")).lower()
525
+
526
+ # ํ•œ๊ตญ ๊ด€๋ จ ์ปจํ…์ธ  ํ•„ํ„ฐ๋ง
527
+ is_korean_content = any(domain in url or domain in channel for domain in korean_domains) or \
528
+ any(keyword in title.lower() for keyword in korean_keywords)
529
+
530
+ if not is_korean_content:
531
+ filtered_articles.append({
532
+ "index": idx,
533
+ "title": result.get("title", "์ œ๋ชฉ ์—†์Œ"),
534
+ "link": url,
535
+ "snippet": result.get("snippet", "๋‚ด์šฉ ์—†์Œ"),
536
+ "channel": result.get("channel", result.get("source", "์•Œ ์ˆ˜ ์—†์Œ")),
537
+ "time": result.get("time", result.get("date", "์•Œ ์ˆ˜ ์—†๋Š” ์‹œ๊ฐ„")),
538
+ "image_url": result.get("img", result.get("thumbnail", "")),
539
+ "translated_query": translated_query
540
+ })
541
+
542
+ return "", filtered_articles
543
  except Exception as e:
544
  return f"๊ฒฐ๊ณผ ์ฒ˜๋ฆฌ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}", []
545
 
 
548
  return format_results_from_raw(response_data)
549
 
550
 
551
+ def search_and_display(query, country, articles_state, progress=gr.Progress()):
552
+ with ThreadPoolExecutor(max_workers=3) as executor:
553
+ progress(0, desc="๊ฒ€์ƒ‰์–ด ๋ฒˆ์—ญ ์ค‘...")
554
+ future_translation = executor.submit(translate_query, query, country)
555
+ translated_query = future_translation.result()
556
+ translated_display = f"**์›๋ณธ ๊ฒ€์ƒ‰์–ด:** {query}\n**๋ฒˆ์—ญ๋œ ๊ฒ€์ƒ‰์–ด:** {translated_query}" if translated_query != query else f"**๊ฒ€์ƒ‰์–ด:** {query}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
557
 
558
+ progress(0.3, desc="๊ฒ€์ƒ‰ ์ค‘...")
559
+ response_data = search_serphouse(query, country)
560
 
561
+ progress(0.6, desc="๊ฒฐ๊ณผ ์ฒ˜๋ฆฌ ์ค‘...")
562
+ error_message, articles = format_results_from_raw(response_data)
563
 
564
+ outputs = []
565
+ outputs.append(gr.update(value="๊ฒ€์ƒ‰์„ ์ง„ํ–‰์ค‘์ž…๋‹ˆ๋‹ค...", visible=True))
566
+ outputs.append(gr.update(value=translated_display, visible=True))
 
 
 
567
 
568
+ if error_message:
569
+ outputs.append(gr.update(value=error_message, visible=True))
570
+ for comp in article_components:
571
+ outputs.extend([
572
+ gr.update(visible=False), gr.update(), gr.update(),
573
+ gr.update(), gr.update()
574
+ ])
575
+ articles_state = []
576
  else:
577
+ outputs.append(gr.update(value="", visible=False))
578
+ if not error_message and articles:
579
+ futures = []
580
+ for article in articles:
581
+ future = executor.submit(translate_to_korean, article['snippet'])
582
+ futures.append((article, future))
583
+
584
+ progress(0.8, desc="๋ฒˆ์—ญ ์ฒ˜๋ฆฌ ์ค‘...")
585
+ for article, future in futures:
586
+ article['korean_summary'] = future.result()
587
+
588
+ total_articles = len(articles)
589
+ for idx, comp in enumerate(article_components):
590
+ progress((idx + 1) / total_articles, desc=f"๊ฒฐ๊ณผ ํ‘œ์‹œ ์ค‘... {idx + 1}/{total_articles}")
591
+ if idx < len(articles):
592
+ article = articles[idx]
593
+ image_url = article['image_url']
594
+ image_update = gr.update(value=image_url, visible=True) if image_url and not image_url.startswith('data:image') else gr.update(value=None, visible=False)
595
+
596
+ outputs.extend([
597
+ gr.update(visible=True),
598
+ gr.update(value=f"### [{article['title']}]({article['link']})"),
599
+ image_update,
600
+ gr.update(value=f"**์š”์•ฝ:** {article['snippet']}\n\n**ํ•œ๊ธ€ ์š”์•ฝ:** {article['korean_summary']}"),
601
+ gr.update(value=f"**์ถœ์ฒ˜:** {article['channel']} | **์‹œ๊ฐ„:** {article['time']}")
602
+ ])
603
+ else:
604
+ outputs.extend([
605
+ gr.update(visible=False), gr.update(), gr.update(),
606
+ gr.update(), gr.update()
607
+ ])
608
+ articles_state = articles
609
 
610
+ progress(1.0, desc="์™„๋ฃŒ!")
611
+ outputs.append(articles_state)
612
+ outputs[0] = gr.update(value="", visible=False)
 
613
 
614
+ return outputs
 
615
 
616
+ def get_region_countries(region):
617
+ """์„ ํƒ๋œ ์ง€์—ญ์˜ ๊ตญ๊ฐ€ ๋ฐ ์–ธ์–ด ์ •๋ณด ๋ฐ˜ํ™˜"""
618
+ if region == "๋™์•„์‹œ์•„":
619
+ return COUNTRY_LOCATIONS_EAST_ASIA, COUNTRY_LANGUAGES_EAST_ASIA
620
+ elif region == "๋™๋‚จ์•„์‹œ์•„/์˜ค์„ธ์•„๋‹ˆ์•„":
621
+ return COUNTRY_LOCATIONS_SOUTHEAST_ASIA_OCEANIA, COUNTRY_LANGUAGES_SOUTHEAST_ASIA_OCEANIA
622
+ elif region == "๋™์œ ๋Ÿฝ":
623
+ return COUNTRY_LOCATIONS_EAST_EUROPE, COUNTRY_LANGUAGES_EAST_EUROPE
624
+ elif region == "์„œ์œ ๋Ÿฝ":
625
+ return COUNTRY_LOCATIONS_WEST_EUROPE, COUNTRY_LANGUAGES_WEST_EUROPE
626
+ elif region == "์ค‘๋™/์•„ํ”„๋ฆฌ์นด":
627
+ return COUNTRY_LOCATIONS_ARAB_AFRICA, COUNTRY_LANGUAGES_ARAB_AFRICA
628
+ elif region == "์•„๋ฉ”๋ฆฌ์นด":
629
+ return COUNTRY_LOCATIONS_AMERICA, COUNTRY_LANGUAGES_AMERICA
630
+ return {}, {}
631
 
632
+ def search_global(query, region, articles_state_global):
633
+ """์ง€์—ญ๋ณ„ ๊ฒ€์ƒ‰ ํ•จ์ˆ˜"""
634
+ status_msg = f"{region} ์ง€์—ญ ๊ฒ€์ƒ‰์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค..."
635
+ all_results = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
636
 
637
+ outputs = [
638
+ gr.update(value=status_msg, visible=True),
639
+ gr.update(value=f"**๊ฒ€์ƒ‰์–ด:** {query}", visible=True),
640
+ ]
641
 
642
+ for _ in global_article_components:
 
643
  outputs.extend([
644
+ gr.update(visible=False), gr.update(), gr.update(),
645
+ gr.update(), gr.update()
 
 
 
 
646
  ])
647
+ outputs.append([])
648
+
649
  yield outputs
650
 
651
+ # ์„ ํƒ๋œ ์ง€์—ญ์˜ ๊ตญ๊ฐ€ ์ •๋ณด ๊ฐ€์ ธ์˜ค๊ธฐ
652
+ locations, languages = get_region_countries(region)
653
+ total_countries = len(locations)
654
+
655
+ for idx, (country, location) in enumerate(locations.items(), 1):
656
+ try:
657
+ status_msg = f"{region} - {country} ๊ฒ€์ƒ‰ ์ค‘... ({idx}/{total_countries} ๊ตญ๊ฐ€)"
658
+ outputs[0] = gr.update(value=status_msg, visible=True)
659
+ yield outputs
 
 
 
660
 
661
+ error_message, articles = serphouse_search(query, country)
662
+ if not error_message and articles:
663
+ for article in articles:
664
+ article['source_country'] = country
665
+ article['region'] = region
666
 
667
+ all_results.extend(articles)
668
+ sorted_results = sorted(all_results, key=lambda x: x.get('time', ''), reverse=True)
669
 
670
+ seen_urls = set()
671
+ unique_results = []
672
+ for article in sorted_results:
673
+ url = article.get('link', '')
674
+ if url not in seen_urls:
675
+ seen_urls.add(url)
676
+ unique_results.append(article)
677
+
678
+ unique_results = unique_results[:MAX_GLOBAL_RESULTS]
679
+
680
+ outputs = [
681
+ gr.update(value=f"{region} - {idx}/{total_countries} ๊ตญ๊ฐ€ ๊ฒ€์ƒ‰ ์™„๋ฃŒ\nํ˜„์žฌ๊นŒ์ง€ ๋ฐœ๊ฒฌ๋œ ๋‰ด์Šค: {len(unique_results)}๊ฑด", visible=True),
682
+ gr.update(value=f"**๊ฒ€์ƒ‰์–ด:** {query} | **์ง€์—ญ:** {region}", visible=True),
683
+ ]
684
+
685
+ for idx, comp in enumerate(global_article_components):
686
+ if idx < len(unique_results):
687
+ article = unique_results[idx]
688
+ image_url = article.get('image_url', '')
689
+ image_update = gr.update(value=image_url, visible=True) if image_url and not image_url.startswith('data:image') else gr.update(value=None, visible=False)
690
+
691
+ korean_summary = translate_to_korean(article['snippet'])
692
+
693
  outputs.extend([
694
  gr.update(visible=True),
695
+ gr.update(value=f"### [{article['title']}]({article['link']})"),
696
+ image_update,
697
+ gr.update(value=f"**์š”์•ฝ:** {article['snippet']}\n\n**ํ•œ๊ธ€ ์š”์•ฝ:** {korean_summary}"),
698
+ gr.update(value=f"**์ถœ์ฒ˜:** {article['channel']} | **๊ตญ๊ฐ€:** {article['source_country']} | **์ง€์—ญ:** {article['region']} | **์‹œ๊ฐ„:** {article['time']}")
 
 
 
 
 
 
 
699
  ])
700
  else:
701
  outputs.extend([
702
  gr.update(visible=False),
703
  gr.update(),
704
  gr.update(),
705
+ gr.update(),
706
+ gr.update()
 
707
  ])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
708
 
709
+ outputs.append(unique_results)
710
+ yield outputs
711
+
712
  except Exception as e:
713
+ print(f"Error searching {country}: {str(e)}")
714
+ continue
715
+
716
+ final_status = f"{region} ๊ฒ€์ƒ‰ ์™„๋ฃŒ! ์ด {len(unique_results)}๊ฐœ์˜ ๋‰ด์Šค๊ฐ€ ๋ฐœ๊ฒฌ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."
717
+ outputs[0] = gr.update(value=final_status, visible=True)
718
+ yield outputs
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
719
 
720
  css = """
721
  /* ์ „์—ญ ์Šคํƒ€์ผ */
 
784
  border-radius: 4px !important;
785
  }
786
 
787
+ /* ํ”„๋กœ๊ทธ๋ ˆ์Šค๋ฐ” ์ปจํ…Œ์ด๋„ˆ */
788
+ .progress-container {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
789
  position: fixed;
790
  top: 0;
791
  left: 0;
792
  width: 100%;
793
+ height: 6px;
794
+ background: #e0e0e0;
795
  z-index: 1000;
796
  }
797
 
798
+ /* ํ”„๋กœ๊ทธ๋ ˆ์Šค๋ฐ” */
799
  .progress-bar {
800
  height: 100%;
801
+ background: linear-gradient(90deg, #2196F3, #00BCD4);
802
+ box-shadow: 0 0 10px rgba(33, 150, 243, 0.5);
803
  transition: width 0.3s ease;
804
+ animation: progress-glow 1.5s ease-in-out infinite;
 
 
 
 
805
  }
806
 
807
+ /* ํ”„๋กœ๊ทธ๋ ˆ์Šค ํ…์ŠคํŠธ */
808
+ .progress-text {
809
+ position: fixed;
810
+ top: 8px;
811
+ left: 50%;
812
+ transform: translateX(-50%);
813
+ background: #333;
814
+ color: white;
815
+ padding: 4px 12px;
816
+ border-radius: 15px;
817
+ font-size: 14px;
818
+ z-index: 1001;
819
+ box-shadow: 0 2px 5px rgba(0,0,0,0.2);
820
  }
821
 
822
+ /* ํ”„๋กœ๊ทธ๋ ˆ์Šค๋ฐ” ์• ๋‹ˆ๋ฉ”์ด์…˜ */
823
+ @keyframes progress-glow {
824
+ 0% {
825
+ box-shadow: 0 0 5px rgba(33, 150, 243, 0.5);
826
+ }
827
+ 50% {
828
+ box-shadow: 0 0 20px rgba(33, 150, 243, 0.8);
829
+ }
830
+ 100% {
831
+ box-shadow: 0 0 5px rgba(33, 150, 243, 0.5);
832
+ }
833
  }
834
 
835
  /* ๋ฐ˜์‘ํ˜• ๋””์ž์ธ */
836
  @media (max-width: 768px) {
837
+ .group {
838
  padding: 10px;
839
  margin-bottom: 15px;
840
  }
841
 
842
+ .progress-text {
843
+ font-size: 12px;
844
+ padding: 3px 10px;
845
  }
846
  }
 
847
 
848
+ /* ๋กœ๋”ฉ ์ƒํƒœ ํ‘œ์‹œ ๊ฐœ์„  */
849
+ .loading {
850
+ opacity: 0.7;
851
+ pointer-events: none;
852
+ transition: opacity 0.3s ease;
853
+ }
854
 
855
+ /* ๊ฒฐ๊ณผ ์ปจํ…Œ์ด๋„ˆ ์• ๋‹ˆ๋ฉ”์ด์…˜ */
856
+ .group {
857
+ transition: all 0.3s ease;
858
+ opacity: 0;
859
+ transform: translateY(20px);
860
+ }
861
 
862
+ .group.visible {
863
+ opacity: 1;
864
+ transform: translateY(0);
865
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
866
 
867
+ /* Examples ์Šคํƒ€์ผ๋ง */
868
+ .examples-table {
869
+ margin-top: 10px !important;
870
+ margin-bottom: 20px !important;
871
+ }
872
 
873
+ .examples-table button {
874
+ background-color: #f0f0f0 !important;
875
+ border: 1px solid #ddd !important;
876
+ border-radius: 4px !important;
877
+ padding: 5px 10px !important;
878
+ margin: 2px !important;
879
+ transition: all 0.3s ease !important;
880
+ }
881
 
882
+ .examples-table button:hover {
883
+ background-color: #e0e0e0 !important;
884
+ transform: translateY(-1px) !important;
885
+ box-shadow: 0 2px 5px rgba(0,0,0,0.1) !important;
886
+ }
 
 
 
 
 
 
 
 
 
 
887
 
888
+ .examples-table .label {
889
+ font-weight: bold !important;
890
+ color: #444 !important;
891
+ margin-bottom: 5px !important;
892
+ }
893
+ """
894
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
895
 
896
+ def get_article_content(url):
897
+ try:
898
+ headers = {
899
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
900
+ }
901
+ response = requests.get(url, headers=headers)
902
+ soup = BeautifulSoup(response.content, 'html.parser')
903
+
904
+ # ์ผ๋ฐ˜์ ์ธ ๊ธฐ์‚ฌ ๋ณธ๋ฌธ ์ปจํ…Œ์ด๋„ˆ ๊ฒ€์ƒ‰
905
+ article_body = None
906
+ possible_content_elements = [
907
+ soup.find('article'),
908
+ soup.find('div', class_='article-body'),
909
+ soup.find('div', class_='content'),
910
+ soup.find('div', {'id': 'article-body'})
911
+ ]
912
+
913
+ for element in possible_content_elements:
914
+ if element:
915
+ article_body = element
916
+ break
917
+
918
+ if article_body:
919
+ # ๋ถˆํ•„์š”ํ•œ ์š”์†Œ ์ œ๊ฑฐ
920
+ for tag in article_body.find_all(['script', 'style', 'nav', 'header', 'footer']):
921
+ tag.decompose()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
922
 
923
+ content = ' '.join([p.get_text().strip() for p in article_body.find_all('p') if p.get_text().strip()])
924
+ else:
925
+ content = ' '.join([p.get_text().strip() for p in soup.find_all('p') if p.get_text().strip()])
926
+
927
+ return content
928
+ except Exception as e:
929
+ return f"Error crawling content: {str(e)}"
930
+
931
+ def respond(
932
+ url,
933
+ history: list[tuple[str, str]],
934
+ system_message,
935
+ max_tokens,
936
+ temperature,
937
+ top_p,
938
+ ):
939
+ if not url.startswith('http'):
940
+ history.append((url, "์˜ฌ๋ฐ”๋ฅธ URL์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."))
941
+ return history
942
 
943
+ try:
944
+ # ๊ธฐ์‚ฌ ๋‚ด์šฉ ์ถ”์ถœ
945
+ article_content = get_article_content(url)
946
+
947
+ # 2๋‹จ๊ณ„ ํ”„๋กœ์„ธ์Šค๋ฅผ ์œ„ํ•œ ํ”„๋กฌํ”„ํŠธ ๊ตฌ์„ฑ
948
+ translation_prompt = f"""๋‹ค์Œ ์ž‘์—…์„ ์ˆœ์ฐจ์ ์œผ๋กœ ์ˆ˜ํ–‰ํ•˜์„ธ์š”:
949
+
950
+ 1๋‹จ๊ณ„: ๋ฒˆ์—ญ
951
+ ์•„๋ž˜ ์˜๋ฌธ ๊ธฐ์‚ฌ๋ฅผ ํ•œ๊ตญ์–ด๋กœ ์ •ํ™•ํ•˜๊ฒŒ ๋ฒˆ์—ญํ•˜์„ธ์š”.
952
+ ๊ตฌ๋ถ„์„ : ===๋ฒˆ์—ญ ์‹œ์ž‘===
953
+ {article_content}
954
+ ๊ตฌ๋ถ„์„ : ===๋ฒˆ์—ญ ๋===
955
+
956
+ 2๋‹จ๊ณ„: ๊ธฐ์‚ฌ ์ž‘์„ฑ
957
+ ์œ„์˜ ๋ฒˆ์—ญ๋œ ๋‚ด์šฉ์„ ๋ฐ”ํƒ•์œผ๋กœ ์ƒˆ๋กœ์šด ํ•œ๊ตญ์–ด ๊ธฐ์‚ฌ๋ฅผ ์ž‘์„ฑํ•˜์„ธ์š”.
958
+ ๋‹ค์Œ ํ˜•์‹์„ ๋ฐ˜๋“œ์‹œ ์ค€์ˆ˜ํ•˜์„ธ์š”:
959
+ - ์ œ๋ชฉ: [ํ—ค๋“œ๋ผ์ธ]
960
+ - ๋ถ€์ œ: [์„œ๋ธŒํ—ค๋“œ๋ผ์ธ]
961
+ - ๋ณธ๋ฌธ: [๊ธฐ์‚ฌ ๋‚ด์šฉ]
962
+ - ์ž‘์„ฑ ๊ทœ์น™:
963
+ * ๋ฌธ์žฅ์€ '๋‹ค.'๋กœ ๋๋‚˜์•ผ ํ•จ
964
+ * ์‹ ๋ฌธ ๊ธฐ์‚ฌ ํ˜•์‹ ์ค€์ˆ˜
965
+ * ๋‹จ๋ฝ ๊ตฌ๋ถ„์„ ๋ช…ํ™•ํžˆ ํ•  ๊ฒƒ
966
+ * ํ•ต์‹ฌ ์ •๋ณด๋ฅผ ์•ž๋ถ€๋ถ„์— ๋ฐฐ์น˜
967
+ * ์ธ์šฉ๊ตฌ๋Š” ๋”ฐ์˜ดํ‘œ๋กœ ์ฒ˜๋ฆฌ
968
+
969
+ ๊ฐ ๋‹จ๊ณ„๋Š” '===๋ฒˆ์—ญ===', '===๊ธฐ์‚ฌ==='๋กœ ๊ตฌ๋ถ„ํ•˜์—ฌ ์ถœ๋ ฅํ•˜์„ธ์š”.
970
+ """
971
 
972
+ messages = [
973
+ {
974
+ "role": "system",
975
+ "content": """๋‹น์‹ ์€ ์ „๋ฌธ ๋ฒˆ์—ญ๊ฐ€์ด์ž ๊ธฐ์ž์ž…๋‹ˆ๋‹ค.
976
+ ๋ชจ๋“  ์ž‘์—…์€ ๋ฐ˜๋“œ์‹œ ๋‹ค์Œ ๋‘ ๋‹จ๊ณ„๋กœ ์ง„ํ–‰ํ•˜๊ณ , ๊ฐ ๋‹จ๊ณ„๋ฅผ ๋ช…ํ™•ํžˆ ๊ตฌ๋ถ„ํ•˜์—ฌ ์ถœ๋ ฅํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค:
977
+ 1. ์›๋ฌธ ๋ฒˆ์—ญ: ===๋ฒˆ์—ญ=== ํ‘œ์‹œ ํ›„ ์ •ํ™•ํ•œ ํ•œ๊ตญ์–ด ๋ฒˆ์—ญ ์ œ๊ณต
978
+ 2. ๊ธฐ์‚ฌ ์ž‘์„ฑ: ===๊ธฐ์‚ฌ=== ํ‘œ์‹œ ํ›„ ๋ฒˆ์—ญ๋ณธ์„ ๊ธฐ๋ฐ˜์œผ๋กœ ํ•œ๊ตญ์–ด ๋‰ด์Šค ๊ธฐ์‚ฌ ์ž‘์„ฑ
979
+ ๋‘ ๋‹จ๊ณ„๋ฅผ ๊ฑด๋„ˆ๋›ฐ๊ฑฐ๋‚˜ ํ†ตํ•ฉํ•˜์ง€ ๋ง๊ณ  ๋ฐ˜๋“œ์‹œ ์ˆœ์ฐจ์ ์œผ๋กœ ์ง„ํ–‰ํ•˜์„ธ์š”."""
980
+ },
981
+ {"role": "user", "content": translation_prompt}
982
+ ]
983
 
984
+ history.append((url, "๋ฒˆ์—ญ ๋ฐ ๊ธฐ์‚ฌ ์ž‘์„ฑ์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค..."))
985
+
986
+ full_response = ""
987
+ current_section = ""
988
+
989
+ for message in client.chat.completions.create(
990
+ model="CohereForAI/c4ai-command-r-plus-08-2024",
991
+ max_tokens=max_tokens,
992
+ stream=True,
993
+ temperature=temperature,
994
+ top_p=top_p,
995
+ messages=messages,
996
+ ):
997
+ if hasattr(message.choices[0].delta, 'content'):
998
+ token = message.choices[0].delta.content
999
+ if token:
1000
+ full_response += token
1001
+ # ์„น์…˜ ๊ตฌ๋ถ„์ž ํ™•์ธ ๋ฐ ํฌ๋งทํŒ…
1002
+ if "===๋ฒˆ์—ญ===" in token or "===๊ธฐ์‚ฌ===" in token:
1003
+ current_section = token.strip()
1004
+ full_response += "\n\n"
1005
+
1006
+ history[-1] = (url, full_response)
1007
+ yield history
1008
 
1009
+ except Exception as e:
1010
+ error_message = f"์ฒ˜๋ฆฌ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"
1011
+ history.append((url, error_message))
1012
+ yield history
1013
 
1014
+ return history
1015
 
1016
+ with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", css=css, title="NewsAI ์„œ๋น„์Šค") as iface:
1017
  with gr.Tabs():
1018
  # ๊ตญ๊ฐ€๋ณ„ ํƒญ
1019
  with gr.Tab("๊ตญ๊ฐ€๋ณ„"):
 
1029
  value="United States"
1030
  )
1031
 
1032
+ # Examples ์ถ”๊ฐ€
1033
+ gr.Examples(
1034
+ examples=[
1035
+ "artificial intelligence",
1036
+ "NVIDIA",
1037
+ "OPENAI",
1038
+ "META LLAMA",
1039
+ "black forest labs",
1040
+ "GOOGLE gemini",
1041
+ "anthropic Claude",
1042
+ "X.AI",
1043
+ "HUGGINGFACE",
1044
+ "HYNIX",
1045
+ "Large Language model",
1046
+ "CHATGPT",
1047
+ "StabilityAI",
1048
+ "MISTRALAI",
1049
+ "QWEN",
1050
+ "MIDJOURNEY",
1051
+ "GPU"
1052
+ ],
1053
+ inputs=query,
1054
+ label="์ž์ฃผ ์‚ฌ์šฉ๋˜๋Š” ๊ฒ€์ƒ‰์–ด"
1055
+ )
1056
+
1057
  status_message = gr.Markdown("", visible=True)
1058
  translated_query_display = gr.Markdown(visible=False)
1059
  search_button = gr.Button("๊ฒ€์ƒ‰", variant="primary")
1060
+
1061
 
1062
  progress = gr.Progress()
1063
  articles_state = gr.State([])
 
1116
  'index': i,
1117
  })
1118
 
1119
+
1120
+ # AI ๋ฒˆ์—ญ ํƒญ ์ถ”๊ฐ€
1121
+ with gr.Tab("AI ๊ธฐ์‚ฌ ์ƒ์„ฑ"):
1122
+ gr.Markdown("๋‰ด์Šค URL์„ ์ž…๋ ฅํ•˜๋ฉด AI๊ฐ€ ํ•œ๊ตญ์–ด๋กœ ๋ฒˆ์—ญํ•˜์—ฌ ๊ธฐ์‚ฌ ํ˜•์‹์œผ๋กœ ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค.")
1123
+
1124
  with gr.Column():
1125
+ chatbot = gr.Chatbot(height=600)
1126
+
1127
+ with gr.Row():
1128
+ url_input = gr.Textbox(
1129
+ label="๋‰ด์Šค URL",
1130
+ placeholder="https://..."
1131
+ )
1132
+
1133
+ with gr.Accordion("๊ณ ๊ธ‰ ์„ค์ •", open=False):
1134
+ system_message = gr.Textbox(
1135
+ value="""You are a professional translator and journalist. Follow these steps strictly:
1136
+ 1. TRANSLATION
1137
+ - Start with ===๋ฒˆ์—ญ=== marker
1138
+ - Provide accurate Korean translation
1139
+ - Maintain original meaning and context
1140
+
1141
+ 2. ARTICLE WRITING
1142
+ - Start with ===๊ธฐ์‚ฌ=== marker
1143
+ - Write a new Korean news article based on the translation
1144
+ - Follow newspaper article format
1145
+ - Use formal news writing style
1146
+ - End sentences with '๋‹ค.'
1147
+ - Include headline and subheadline
1148
+ - Organize paragraphs clearly
1149
+ - Put key information first
1150
+ - Use quotes appropriately
1151
+
1152
+ IMPORTANT:
1153
+ - Must complete both steps in order
1154
+ - Clearly separate each section with markers
1155
+ - Never skip or combine steps""",
1156
+ label="System message"
1157
+ )
1158
+
1159
+ max_tokens = gr.Slider(
1160
+ minimum=1,
1161
+ maximum=7800,
1162
+ value=7624,
1163
+ step=1,
1164
+ label="Max new tokens"
1165
+ )
1166
+ temperature = gr.Slider(
1167
+ minimum=0.1,
1168
+ maximum=4.0,
1169
+ value=0.7,
1170
+ step=0.1,
1171
+ label="Temperature"
1172
+ )
1173
+ top_p = gr.Slider(
1174
+ minimum=0.1,
1175
+ maximum=1.0,
1176
+ value=0.95,
1177
+ step=0.05,
1178
+ label="Top-P"
1179
+ )
1180
+
1181
+ translate_button = gr.Button("๊ธฐ์‚ฌ ์ƒ์„ฑ", variant="primary")
1182
+
1183
+ # ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ
1184
+ translate_button.click(
1185
+ fn=respond,
1186
+ inputs=[
1187
+ url_input,
1188
+ chatbot,
1189
+ system_message,
1190
+ max_tokens,
1191
+ temperature,
1192
+ top_p,
1193
+ ],
1194
+ outputs=chatbot
1195
+ )
1196
+
1197
 
1198
+
1199
+
1200
  # ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ ๋ถ€๋ถ„
1201
  # ๊ตญ๊ฐ€๋ณ„ ํƒญ ์ด๋ฒคํŠธ
1202
  search_outputs = [status_message, translated_query_display, gr.Markdown(visible=False)]
 
1230
  show_progress=True
1231
  )
1232
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1233
  iface.launch(
1234
  server_name="0.0.0.0",
1235
  server_port=7860,
1236
  share=True,
1237
+ auth=("ai","news"),
1238
  ssl_verify=False,
1239
  show_error=True
1240
+ )