openfree commited on
Commit
8619bbc
·
verified ·
1 Parent(s): 89fcc58

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -86
app.py CHANGED
@@ -587,93 +587,78 @@ def create_main_interface():
587
  return ["", None, gr.update(active_key="error"), gr.update(open=False)]
588
 
589
  async def execute_search_and_generate(query, setting):
590
- try:
591
- print(f"Executing web search for query: {query}") # 디버깅용
592
-
593
- # 검색 실행
594
- url = "https://api.serphouse.com/serp/live"
595
-
596
- # 날짜 범위 설정
597
- now = datetime.utcnow()
598
- yesterday = now - timedelta(days=1)
599
- date_range = f"{yesterday.strftime('%Y-%m-%d')},{now.strftime('%Y-%m-%d')}"
600
-
601
- payload = {
602
- "data": {
603
- "q": query,
604
- "domain": "google.com",
605
- "loc": "United States",
606
- "lang": "en",
607
- "device": "desktop",
608
- "serp_type": "news", # 뉴스 검색으로 변경
609
- "page": "1",
610
- "num": "10",
611
- "date_range": date_range,
612
- "sort_by": "date"
613
- }
614
- }
615
-
616
- headers = {
617
- "accept": "application/json",
618
- "content-type": "application/json",
619
- "authorization": "Bearer V38CNn4HXpLtynJQyOeoUensTEYoFy8PBUxKpDqAW1pawT1vfJ2BWtPQ98h6"
620
- }
621
-
622
- # 세션 설정 및 재시도 로직 추가
623
- session = requests.Session()
624
- retries = Retry(total=3, backoff_factor=0.5)
625
- session.mount('https://', HTTPAdapter(max_retries=retries))
626
-
627
- print("Sending search request...") # 디버깅용
628
- response = session.post(url, json=payload, headers=headers, timeout=(5, 15))
629
- response.raise_for_status()
630
- results = response.json()
631
- print(f"Search results received: {len(results.get('results', []))} items") # 디버깅용
632
-
633
- # 검색 결과를 HTML로 변환
634
- search_content = "<div class='search-summary'><h2>Search Results</h2>"
635
- if 'results' in results and isinstance(results['results'], list):
636
- search_results = results['results']
637
- if len(search_results) > 5:
638
- search_results = search_results[:5]
639
-
640
- for result in search_results:
641
- title = result.get('title', 'No Title')
642
- url = result.get('url', '#')
643
- snippet = result.get('snippet', 'No description available')
644
- time = result.get('time', '')
 
 
 
 
 
 
 
 
645
 
646
- search_content += f"""
647
- <div class="search-item">
648
- <h3><a href="{url}" target="_blank">{title}</a></h3>
649
- <p>{snippet}</p>
650
- <span class="search-time">{time}</span>
651
- </div>
652
- """
653
- search_content += "</div>"
654
-
655
- # 검색 결과를 포함한 프롬프트 생성
656
- enhanced_prompt = f"""Based on these recent news results, create a visually appealing and informative response:
657
- {search_content}
658
-
659
- Original query: {query}
660
-
661
- Create a comprehensive visual response that incorporates relevant information from the news results.
662
- """
663
-
664
- # async generator를 처리하기 위한 수정
665
- async for result in demo_instance.generation_code(enhanced_prompt, setting):
666
- final_result = result
667
- return final_result
668
-
669
- except Exception as e:
670
- print(f"Search error: {str(e)}")
671
- return [
672
- "",
673
- None,
674
- gr.update(active_key="error"),
675
- gr.update(open=False)
676
- ]
677
 
678
  def execute_code(query: str):
679
  if not query or query.strip() == '':
 
587
  return ["", None, gr.update(active_key="error"), gr.update(open=False)]
588
 
589
  async def execute_search_and_generate(query, setting):
590
+ try:
591
+ # 검색 실행
592
+ url = "https://api.serphouse.com/serp/live"
593
+ payload = {
594
+ "data": {
595
+ "q": query,
596
+ "domain": "google.com",
597
+ "lang": "en",
598
+ "device": "desktop",
599
+ "serp_type": "news", # 뉴스 검색으로 변경
600
+ "page": "1",
601
+ "num": "10"
602
+ }
603
+ }
604
+ headers = {
605
+ "accept": "application/json",
606
+ "content-type": "application/json",
607
+ "authorization": "Bearer V38CNn4HXpLtynJQyOeoUensTEYoFy8PBUxKpDqAW1pawT1vfJ2BWtPQ98h6"
608
+ }
609
+
610
+ response = requests.post(url, headers=headers, json=payload)
611
+ results = response.json()
612
+
613
+ # 검색 결과를 HTML로 변환하고 요약
614
+ search_summary = "<div class='search-results'>\n"
615
+ search_summary += "<h2>최신 뉴스 검색 결과</h2>\n"
616
+
617
+ if 'results' in results and 'news' in results['results']:
618
+ for item in results['results']['news'][:5]: # 상위 5개 결과만 사용
619
+ search_summary += f"""
620
+ <div class="search-item">
621
+ <h3><a href="{item['url']}" target="_blank">{item['title']}</a></h3>
622
+ <p>{item['snippet']}</p>
623
+ <div class="search-meta">
624
+ <span class="source">{item['channel']}</span>
625
+ <span class="time">{item['time']}</span>
626
+ </div>
627
+ </div>
628
+ """
629
+ search_summary += "</div>"
630
+
631
+ # 검색 결과를 포함한 향상된 프롬프트 생성
632
+ enhanced_prompt = f"""Based on the latest news search results, create a comprehensive and visually appealing response:
633
+
634
+ Search Query: {query}
635
+
636
+ Search Results Summary:
637
+ {search_summary}
638
+
639
+ Please create a response that:
640
+ 1. Summarizes the key information from the search results
641
+ 2. Presents the information in a clear and organized way
642
+ 3. Uses appropriate HTML formatting for better visual presentation
643
+ 4. Includes relevant quotes or statistics when available
644
+ 5. Provides proper attribution to sources
645
+
646
+ Response should be in HTML format with appropriate styling.
647
+ """
648
+
649
+ # async generator를 처리하기 위한 수정
650
+ async for result in demo_instance.generation_code(enhanced_prompt, setting):
651
+ final_result = result
652
+ return final_result
653
 
654
+ except Exception as e:
655
+ print(f"Search error: {str(e)}")
656
+ return [
657
+ "",
658
+ None,
659
+ gr.update(active_key="error"),
660
+ gr.update(open=False)
661
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
662
 
663
  def execute_code(query: str):
664
  if not query or query.strip() == '':