MariaMaraShe commited on
Commit
fde458a
·
verified ·
1 Parent(s): f0d1264

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -29
app.py CHANGED
@@ -4,7 +4,7 @@ import datetime
4
  import requests
5
  import pytz
6
  import yaml
7
- from bs4 import BeautifulSoup
8
  from tools.final_answer import FinalAnswerTool
9
  web_search = DuckDuckGoSearchTool()
10
 
@@ -39,7 +39,7 @@ def get_current_time_in_timezone(timezone: str) -> str:
39
 
40
  @tool
41
  def visit_webpage(url: str) -> str:
42
- """Извлекает текстовое содержимое веб-страницы по URL с улучшенной обработкой заголовков.
43
  Args:
44
  url: Адрес веб-страницы для чтения
45
  """
@@ -48,39 +48,34 @@ def visit_webpage(url: str) -> str:
48
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
49
  }
50
  response = requests.get(url, headers=headers, timeout=30)
51
- soup = BeautifulSoup(response.text, 'html.parser')
52
 
53
- # Улучшенное извлечение заголовков
54
  headlines = []
55
-
56
- # Поиск заголовков в различных HTML-тегах
57
- headline_tags = ['h1', 'h2', 'h3', 'h4', 'article-title', 'title']
58
- for tag in headline_tags:
59
- headlines.extend([
60
- h.get_text(strip=True)
61
- for h in soup.find_all(tag)
62
- if h.get_text(strip=True)
63
- ])
64
-
65
- # Удаление лишних тегов и скриптов
66
- for tag in soup(['script', 'style', 'meta', 'link']):
67
- tag.decompose()
68
-
69
- # Очистка и фильтрация заголовков
70
- headlines = [
71
- headline for headline in headlines
72
- if len(headline) > 10 and len(headline) < 200
73
  ]
74
 
75
- # Возвращаем текст страницы с выделенными заголовками
76
- full_text = soup.get_text(separator='\n', strip=True)
 
 
 
 
 
 
 
 
 
 
77
 
78
- # Добавляем заголовки в начало текста
79
- if headlines:
80
- headlines_text = "Заголовки:\n" + "\n".join(headlines) + "\n\n"
81
- return headlines_text + full_text
82
 
83
- return full_text
84
 
85
  except Exception as e:
86
  return f"Error fetching webpage: {str(e)}"
 
4
  import requests
5
  import pytz
6
  import yaml
7
+ import re
8
  from tools.final_answer import FinalAnswerTool
9
  web_search = DuckDuckGoSearchTool()
10
 
 
39
 
40
  @tool
41
  def visit_webpage(url: str) -> str:
42
+ """Извлекает текстовое содержимое веб-страницы по URL.
43
  Args:
44
  url: Адрес веб-страницы для чтения
45
  """
 
48
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
49
  }
50
  response = requests.get(url, headers=headers, timeout=30)
 
51
 
52
+ # Извлечение заголовков с помощью регулярных выражений
53
  headlines = []
54
+ patterns = [
55
+ r'<h3[^>]*>(.*?)</h3>',
56
+ r'<h2[^>]*>(.*?)</h2>',
57
+ r'class="[^"]*title[^"]*">(.*?)</h3>'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  ]
59
 
60
+ for pattern in patterns:
61
+ found = re.findall(pattern, response.text, re.DOTALL | re.IGNORECASE)
62
+ headlines.extend(found)
63
+ if len(headlines) >= 5:
64
+ break
65
+
66
+ # Очистка заголовков
67
+ cleaned_headlines = []
68
+ for headline in headlines:
69
+ clean = re.sub(r'<[^>]+>', '', headline).strip()
70
+ if 10 < len(clean) < 200:
71
+ cleaned_headlines.append(clean)
72
 
73
+ # Возврат текста с заголовками
74
+ if cleaned_headlines:
75
+ headlines_text = "Заголовки:\n" + "\n".join(cleaned_headlines[:5]) + "\n\n"
76
+ return headlines_text + response.text
77
 
78
+ return response.text
79
 
80
  except Exception as e:
81
  return f"Error fetching webpage: {str(e)}"