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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
import asyncio
import aiohttp
import csv
import os
import re
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse
import logging
from typing import List, Dict, Optional, Set
import time

# Настройка логирования
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class FastCodeTemplatesParser:
    def __init__(self, csv_file: str = 'fastcode_templates.csv', delay: float = 1.0):
        self.csv_file = csv_file
        self.delay = delay  # Задержка между запросами
        self.base_url = 'https://fastcode.im'
        self.processed_ids: Set[str] = set()
        
        # Создаем CSV файл с заголовками если его нет
        self._init_csv()
        
        # Загружаем уже обработанные ID из CSV
        self._load_processed_ids()
    
    def _init_csv(self):
        """Инициализация CSV файла с заголовками"""
        if not os.path.exists(self.csv_file):
            with open(self.csv_file, 'w', newline='', encoding='utf-8') as file:
                writer = csv.writer(file, quoting=csv.QUOTE_ALL)
                writer.writerow(['source', 'in_source_id', 'prompt', 'solution', 'tags', 'is_answer_a_link', 'has_link'])
    
    def _load_processed_ids(self):
        """Загрузка уже обработанных ID из CSV"""
        if os.path.exists(self.csv_file):
            with open(self.csv_file, 'r', encoding='utf-8') as file:
                reader = csv.DictReader(file)
                for row in reader:
                    if row['in_source_id']:
                        self.processed_ids.add(row['in_source_id'])
        logger.info(f"Загружено {len(self.processed_ids)} уже обработанных шаблонов")
    
    async def fetch_page(self, session: aiohttp.ClientSession, url: str) -> Optional[str]:
        """Получение содержимого страницы"""
        try:
            await asyncio.sleep(self.delay)
            async with session.get(url, timeout=30) as response:
                if response.status == 200:
                    return await response.text()
                else:
                    logger.warning(f"Ошибка {response.status} при загрузке {url}")
                    return None
        except Exception as e:
            logger.error(f"Ошибка при загрузке {url}: {e}")
            return None
    
    async def parse_templates_list_page(self, session: aiohttp.ClientSession, page_num: int) -> List[str]:
        """Парсинг страницы списка шаблонов"""
        url = f"{self.base_url}/Templates?Page={page_num}&TemplatesOnly=True"
        logger.info(f"Парсинг страницы списка шаблонов: {page_num}")
        
        html = await self.fetch_page(session, url)
        if not html:
            return []
        
        soup = BeautifulSoup(html, 'html.parser')
        template_ids = []
        
        # Находим div с id="indexPartial"
        index_partial = soup.find('div', id='indexPartial')
        if not index_partial:
            logger.warning(f"Не найден div#indexPartial на странице {page_num}")
            return []
        
        # Ищем все h3 с классом post_title break-word
        title_headers = index_partial.find_all('h3', class_='post_title break-word')
        logger.info(f"Найдено {len(title_headers)} заголовков на странице {page_num}")
        
        for header in title_headers:
            # Ищем ссылку внутри h3
            link = header.find('a', href=True)
            if link:
                href = link['href']
                # Проверяем, что ссылка начинается с /Templates/
                if href.startswith('/Templates/'):
                    # Извлекаем ID из ссылки
                    match = re.search(r'/Templates/(\d+)', href)
                    if match:
                        template_id = match.group(1)
                        template_ids.append(template_id)
        
        logger.info(f"Найдено {len(template_ids)} валидных шаблонов на странице {page_num}")
        return template_ids
    
    def extract_title(self, soup: BeautifulSoup) -> Optional[str]:
        """Извлечение названия шаблона"""
        # Ищем все div.article
        articles = soup.find_all('div', class_='article')
        
        # Берем первый article который содержит h1
        for article in articles:
            h1 = article.find('h1')
            if h1:
                return h1.get_text().strip()
        
        # Если не найден в article, ищем любой h1
        h1 = soup.find('h1')
        if h1:
            return h1.get_text().strip()
            
        return None
    
    def extract_tags(self, soup: BeautifulSoup) -> List[str]:
        """Извлечение тегов шаблона"""
        tags = []
        
        # Ищем все span с классом tag-label
        tag_labels = soup.find_all('span', class_='tag-label')
        
        for tag_label in tag_labels:
            # Ищем все span с классом label внутри
            label_spans = tag_label.find_all('span', class_='label')
            for span in label_spans:
                tag_text = span.get_text().strip()
                if tag_text:
                    # Разделяем теги, если они объединены через #
                    if '#' in tag_text:
                        individual_tags = [t.strip() for t in tag_text.split('#') if t.strip()]
                        tags.extend(individual_tags)
                    else:
                        tags.append(tag_text)
        
        return list(set(tags))  # Убираем дубликаты
    
    def extract_description(self, soup: BeautifulSoup) -> Optional[str]:
        """Извлечение описания шаблона"""
        # Согласно инструкции, описание в <p class="break-word" style="margin-bottom: 0px;">
        desc_p = soup.find('p', class_='break-word', style='margin-bottom: 0px;')
        if desc_p:
            span = desc_p.find('span', style='white-space: pre-line')
            if span:
                return span.get_text().strip()
        
        # Если не найдено по точному стилю, пробуем искать любой p.break-word с подходящим стилем
        desc_elements = soup.find_all('p', class_='break-word')
        for p in desc_elements:
            style = p.get('style', '')
            if 'margin-bottom: 0px' in style or 'margin-bottom:0px' in style:
                span = p.find('span')
                if span:
                    return span.get_text().strip()
                else:
                    return p.get_text().strip()
        
        return None
    
    def extract_code(self, soup: BeautifulSoup) -> Optional[str]:
        """Извлечение кода шаблона"""
        # Ищем code с классом 1c
        code_element = soup.find('code', class_='1c')
        if code_element:
            return self.clean_1c_code(code_element)
        return None
    
    def clean_1c_code(self, code_element) -> str:
        """Очистка кода 1С с сохранением отступов"""
        # Получаем чистый текст
        code_text = code_element.get_text()
        
        # Заменяем HTML entities
        code_text = code_text.replace('&quot;', '"')
        code_text = code_text.replace('&lt;', '<')
        code_text = code_text.replace('&gt;', '>')
        code_text = code_text.replace('&amp;', '&')
        
        # Нормализуем переносы строк
        code_text = code_text.replace('\r\n', '\n')
        code_text = code_text.replace('\r', '\n')
        
        # Обрабатываем строки, сохраняя отступы
        lines = code_text.split('\n')
        cleaned_lines = []
        
        for line in lines:
            # Удаляем только trailing пробелы, сохраняя leading
            cleaned_line = line.rstrip()
            cleaned_lines.append(cleaned_line)
        
        # Удаляем пустые строки в начале и конце
        while cleaned_lines and not cleaned_lines[0].strip():
            cleaned_lines.pop(0)
        while cleaned_lines and not cleaned_lines[-1].strip():
            cleaned_lines.pop()
        
        return '\n'.join(cleaned_lines)
    
    def extract_comments(self, soup: BeautifulSoup) -> List[str]:
        """Извлечение комментариев"""
        comments = []
        
        comments_section = soup.find('div', id='comments_section')
        if not comments_section:
            return comments
        
        # Ищем все div с id, которые содержат комментарии
        comment_divs = comments_section.find_all('div', id=True)
        
        for comment_div in comment_divs:
            # Пропускаем div с id="last_comment"
            if comment_div.get('id') == 'last_comment':
                continue
            
            # Создаем копию для обработки
            comment_copy = comment_div.__copy__()
            
            # Удаляем первый div с информацией о пользователе
            first_div = comment_copy.find('div')
            if first_div:
                first_div.decompose()
            
            # Удаляем последний div с кнопками
            last_div = comment_copy.find('div', style=lambda x: x and 'margin-top: 15px' in x)
            if last_div:
                last_div.decompose()
            
            # Удаляем hr
            hr_tags = comment_copy.find_all('hr')
            for hr in hr_tags:
                hr.decompose()
            
            # Получаем текст комментария
            comment_text = comment_copy.get_text().strip()
            if comment_text:
                comments.append(comment_text)
        
        return comments
    
    def count_links_in_text(self, text: str) -> int:
        """Подсчет количества ссылок в тексте"""
        # Ищем http/https ссылки
        url_pattern = r'https?://[^\s<>"{}|\\^`\[\]]+'
        links = re.findall(url_pattern, text)
        return len(links)
    
    def has_links_in_text(self, text: str) -> bool:
        """Проверка наличия ссылок в тексте"""
        url_pattern = r'https?://[^\s<>"{}|\\^`\[\]]+'
        return bool(re.search(url_pattern, text))
    
    def format_solution(self, description: str, code: str, comments: List[str]) -> str:
        """Форматирование решения в markdown"""
        solution_parts = []
        
        # Добавляем описание
        if description:
            solution_parts.append(description)
        
        # Добавляем код
        if code:
            solution_parts.append("# Код реализации")
            solution_parts.append(f"```1c\n{code}\n```")
        
        # Добавляем комментарии
        if comments:
            solution_parts.append("# Примечания")
            for comment in comments:
                solution_parts.append(f"- {comment}")
        
        return '\n\n'.join(solution_parts)
    
    async def parse_template(self, session: aiohttp.ClientSession, template_id: str) -> Optional[Dict]:
        """Парсинг отдельного шаблона"""
        if template_id in self.processed_ids:
            logger.debug(f"Шаблон {template_id} уже обработан")
            return None
            
        url = f"{self.base_url}/Templates/{template_id}"
        logger.info(f"Парсинг шаблона {template_id}")
        
        html = await self.fetch_page(session, url)
        if not html:
            return None
        
        soup = BeautifulSoup(html, 'html.parser')
        
        # Извлекаем данные
        title = self.extract_title(soup)
        if not title:
            logger.warning(f"Не найден заголовок для шаблона {template_id}")
            return None
        
        description = self.extract_description(soup)
        code = self.extract_code(soup)
        tags = self.extract_tags(soup)
        comments = self.extract_comments(soup)
        
        # Форматируем решение
        solution = self.format_solution(description or "", code or "", comments)
        
        # Анализируем ссылки
        link_count = self.count_links_in_text(solution)
        has_links = self.has_links_in_text(solution)
        
        result = {
            'source': 'fastcode_Templates',
            'in_source_id': template_id,
            'prompt': title,
            'solution': solution,
            'tags': ','.join(tags) if tags else '',
            'is_answer_a_link': has_links,
            'has_link': link_count if link_count > 0 else None
        }
        
        logger.info(f"Обработан шаблон {template_id}: '{title}'")
        self.processed_ids.add(template_id)
        return result
    
    async def process_templates_batch(self, session: aiohttp.ClientSession, template_ids: List[str]) -> List[Dict]:
        """Обработка пакета шаблонов"""
        tasks = [self.parse_template(session, template_id) for template_id in template_ids]
        results = await asyncio.gather(*tasks, return_exceptions=True)
        
        valid_results = []
        for result in results:
            if isinstance(result, dict):
                valid_results.append(result)
            elif isinstance(result, Exception):
                logger.error(f"Ошибка при обработке шаблона: {result}")
        
        return valid_results
    
    def escape_for_csv(self, text: str) -> str:
        """Экранирование специальных символов для CSV"""
        if not text:
            return text
        
        # Экранируем специальные символы для корректного сохранения в CSV
        text = text.replace('\\', '\\\\')
        text = text.replace('\r\n', '\n')
        text = text.replace('\r', '\n')
        text = text.replace('\n', '\\n')
        text = text.replace('\t', '\\t')
        
        return text
    
    def save_to_csv(self, data: List[Dict]):
        """Сохранение данных в CSV файл"""
        if not data:
            return
        
        with open(self.csv_file, 'a', newline='', encoding='utf-8') as file:
            writer = csv.DictWriter(file, fieldnames=['source', 'in_source_id', 'prompt', 'solution', 'tags', 'is_answer_a_link', 'has_link'], 
                                  quoting=csv.QUOTE_ALL)
            for row in data:
                # Экранируем специальные символы в текстовых полях
                escaped_row = {}
                for key, value in row.items():
                    if isinstance(value, str):
                        escaped_row[key] = self.escape_for_csv(value)
                    else:
                        escaped_row[key] = value
                writer.writerow(escaped_row)
        
        logger.info(f"Сохранено {len(data)} записей в {self.csv_file}")
    
    async def parse_all_pages(self, start_page: int = 1, end_page: int = 36, batch_size: int = 10):
        """Парсинг всех страниц с шаблонами"""
        connector = aiohttp.TCPConnector(limit=20, limit_per_host=10)
        timeout = aiohttp.ClientTimeout(total=60)
        
        async with aiohttp.ClientSession(
            connector=connector,
            timeout=timeout,
            headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
        ) as session:
            
            for page_num in range(start_page, end_page + 1):
                try:
                    logger.info(f"Обработка страницы {page_num} из {end_page}")
                    
                    # Получаем список ID шаблонов со страницы
                    template_ids = await self.parse_templates_list_page(session, page_num)
                    
                    if not template_ids:
                        logger.info(f"Нет шаблонов для обработки на странице {page_num}")
                        continue
                    
                    # Фильтруем уже обработанные шаблоны
                    new_template_ids = [tid for tid in template_ids if tid not in self.processed_ids]
                    
                    logger.info(f"Новых шаблонов для обработки: {len(new_template_ids)}")
                    
                    if not new_template_ids:
                        continue
                    
                    # Обрабатываем шаблоны пакетами
                    for i in range(0, len(new_template_ids), batch_size):
                        batch = new_template_ids[i:i + batch_size]
                        logger.info(f"Обработка пакета {i//batch_size + 1}, шаблонов в пакете: {len(batch)}")
                        
                        # Парсим пакет шаблонов
                        batch_results = await self.process_templates_batch(session, batch)
                        
                        # Сохраняем результаты
                        if batch_results:
                            self.save_to_csv(batch_results)
                        
                        # Пауза между пакетами
                        await asyncio.sleep(2)
                    
                    logger.info(f"Страница {page_num} обработана")
                    
                except Exception as e:
                    logger.error(f"Ошибка при обработке страницы {page_num}: {e}")
                    continue

async def main():
    """Основная функция"""
    parser = FastCodeTemplatesParser(csv_file='fastcode_templates.csv', delay=1.0)
    
    try:
        await parser.parse_all_pages(start_page=1, end_page=36, batch_size=5)
        logger.info("Парсинг завершен")
    except KeyboardInterrupt:
        logger.info("Парсинг прерван пользователем")
    except Exception as e:
        logger.error(f"Критическая ошибка: {e}")

if __name__ == "__main__":
    asyncio.run(main())