AiWicked commited on
Commit
d3f4ae6
·
verified ·
1 Parent(s): 1056355

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -41
app.py CHANGED
@@ -7,56 +7,73 @@ from tools.final_answer import FinalAnswerTool
7
  from Gradio_UI import GradioUI
8
 
9
  @tool
10
- def keyword_research_tool(topic: str, max_results: int) -> str:
11
  """Генерирует релевантные ключевые слова для заданной темы
12
  Args:
13
- topic: Основная тема для генерации ключевых слов
14
- max_results: Максимальное количество возвращаемых ключевых слов
15
  """
16
  import random
17
- from typing import List
18
 
19
- # Базовые модификаторы для расширения темы
20
- modifiers = [
21
- "лучшие", "топ", "как", "советы", "рецепты",
22
- "польза", "вред", "отзывы", "купить", "сделать",
23
- "обзор", "курс", "уроки", "для начинающих",
24
- "2023", "идеи", "примеры", "методы", "технологии",
25
- "тренды", "планы", "стоимость", "бесплатно", "преимущества"
26
- ]
27
-
28
- # Разбиваем тему на основные слова
29
- seed_words = [word.strip() for word in topic.split() if len(word) > 3]
30
 
31
- # Генерируем комбинации
32
- candidates = set()
33
-
34
- # Добавляем базовые варианты
35
- candidates.add(topic)
36
- candidates.add(f"лучшие {topic}")
37
- candidates.add(f"{topic} 2023")
 
 
 
 
 
 
38
 
39
- # Генерируем комбинации с модификаторами
40
- for modifier in modifiers:
41
- candidates.add(f"{modifier} {topic}")
42
- candidates.add(f"{topic} {modifier}")
43
- for word in seed_words:
44
- candidates.add(f"{modifier} {word}")
45
- candidates.add(f"{word} {modifier}")
46
 
47
- # Добавляем вопросы
48
- question_words = ["как", "что", "где", "когда", "почему"]
49
- for qw in question_words:
50
- candidates.add(f"{qw} {topic}")
51
- for word in seed_words:
52
- candidates.add(f"{qw} {word}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
- # Преобразуем в список и перемешиваем
55
- results = list(candidates)
56
- random.shuffle(results)
 
57
 
58
- # Выбираем запрошенное количество
59
- return ", ".join(results[:max(max_results, 1)])
60
 
61
  # Initialize components
62
  final_answer = FinalAnswerTool()
@@ -80,7 +97,7 @@ with open("prompts.yaml", 'r') as stream:
80
  agent = CodeAgent(
81
  tools=[
82
  image_generation_tool,
83
- keyword_research_tool,
84
  final_answer,
85
  DuckDuckGoSearchTool()
86
  ],
 
7
  from Gradio_UI import GradioUI
8
 
9
  @tool
10
+ def generate_keywords(topic: str, max_keywords: int = 30) -> str:
11
  """Генерирует релевантные ключевые слова для заданной темы
12
  Args:
13
+ topic: Тема для генерации (на русском языке)
14
+ max_keywords: Максимальное количество возвращаемых ключевых слов
15
  """
16
  import random
17
+ from collections import deque
18
 
19
+ # Инициализация компонентов генерации
20
+ base_words = [w.strip().lower() for w in topic.split() if len(w) > 2]
21
+ if not base_words:
22
+ return "Необходимо указать более конкретную тему"
 
 
 
 
 
 
 
23
 
24
+ # Паттерны для генерации
25
+ patterns = [
26
+ ["вопросы", "что такое", "как сделать", "почему", "когда", "где найти"],
27
+ ["топ", "лучшие", "рейтинг", "самые популярные"],
28
+ ["методы", "способы", "технологии", "решения"],
29
+ ["обзор", "отзывы", "сравнение", "виды"],
30
+ ["курс", "урок", "обучение", "самоучитель"],
31
+ ["2025", "новинки", "тренды", "будущее"],
32
+ ["для начинающих", "профессиональные", "премиум"],
33
+ ["бесплатно", "купить", "заказать", "стоимость"],
34
+ ["преимущества", "недостатки", "польза", "вред"],
35
+ ["идеи", "примеры", "кейсы", "истории успеха"]
36
+ ]
37
 
38
+ # Генерация вариантов
39
+ keywords = set()
40
+ queue = deque([(0, [], base_words)])
 
 
 
 
41
 
42
+ while queue:
43
+ level, current, remaining = queue.popleft()
44
+
45
+ if level >= 3 or not remaining:
46
+ if current:
47
+ keywords.add(" ".join(current))
48
+ continue
49
+
50
+ # Добавляем паттерны
51
+ if level == 0:
52
+ for pattern_group in patterns:
53
+ for p in pattern_group:
54
+ new_phrase = [p] + current
55
+ queue.append((level+1, new_phrase, remaining))
56
+
57
+ # Комбинируем слова
58
+ for i in range(len(remaining)):
59
+ next_word = remaining[i]
60
+ new_phrase = current + [next_word]
61
+ new_remaining = remaining[:i] + remaining[i+1:]
62
+ queue.append((level+1, new_phrase, new_remaining))
63
+
64
+ # Добавляем модификаторы
65
+ modifiers = ["", "2025", "курс", "обзор", "топ", "способы"]
66
+ for mod in modifiers:
67
+ if mod:
68
+ modified = current + [f"{next_word}-{mod}"]
69
+ queue.append((level+2, modified, new_remaining))
70
 
71
+ # Ранжирование и выборка
72
+ result = sorted(keywords,
73
+ key=lambda x: (-len(x.split()), x))
74
+ random.shuffle(result[:len(result)//2])
75
 
76
+ return ", ".join(result[:max(max_keywords, 1)])
 
77
 
78
  # Initialize components
79
  final_answer = FinalAnswerTool()
 
97
  agent = CodeAgent(
98
  tools=[
99
  image_generation_tool,
100
+ generate_keywords,
101
  final_answer,
102
  DuckDuckGoSearchTool()
103
  ],