95 lines
3.7 KiB
Python
95 lines
3.7 KiB
Python
import os
|
||
import re
|
||
import fitz
|
||
from pathlib import Path
|
||
from datetime import datetime
|
||
|
||
ALL_DIR = Path("/home/matrixhasyou/mutt/exported_emails/all")
|
||
|
||
def parse_pdf(filepath):
|
||
try:
|
||
doc = fitz.open(filepath)
|
||
text = ""
|
||
for page_num in range(min(5, len(doc))):
|
||
text += doc[page_num].get_text()
|
||
doc.close()
|
||
return text
|
||
except Exception as e:
|
||
return ""
|
||
|
||
def is_valid_reply(text):
|
||
text_lower = text.lower()
|
||
formal_markers = [
|
||
'ваше обращение рассмотрено', 'сообщаем вам', 'уведомляем',
|
||
'в соответствии с федеральным законом', 'в пределах компетенции',
|
||
'направляем в ваш адрес', 'в рамках действующего законодательства',
|
||
'уважаемый', 'благодарим за обращение', 'разъясняем', 'доводим до вашего сведения',
|
||
'отказано', 'рассмотрев ваше'
|
||
]
|
||
substantive_markers = [
|
||
'удовлетворено', 'приняты меры', 'выявлены нарушения',
|
||
'обязать устранить', 'проведена проверка', 'выдано предписание',
|
||
'штраф наложен', 'материалы переданы', 'перерасчет'
|
||
]
|
||
indicators = ['ответ', 'рассмотрение', 'сообщаем', 'уведомляем', 'обращение', 'запрос']
|
||
|
||
if any(kw in text_lower for kw in formal_markers + substantive_markers + indicators):
|
||
return True
|
||
return False
|
||
|
||
def extract_meta_from_text(text):
|
||
# Попытка найти Дату, От кого, Кому, Тему в тексте экспортированного письма
|
||
date_match = re.search(r'Date:\s*(.*?)\n', text)
|
||
from_match = re.search(r'From:\s*(.*?)\n', text)
|
||
to_match = re.search(r'To:\s*(.*?)\n', text)
|
||
subject_match = re.search(r'Subject:\s*(.*?)\n', text)
|
||
|
||
return {
|
||
'date': date_match.group(1).strip() if date_match else "",
|
||
'from': from_match.group(1).strip() if from_match else "",
|
||
'to': to_match.group(1).strip() if to_match else "",
|
||
'subject': subject_match.group(1).strip() if subject_match else ""
|
||
}
|
||
|
||
sent_emails = []
|
||
recv_emails = []
|
||
|
||
for f in ALL_DIR.glob("*.pdf"):
|
||
parts = f.stem.split('_', 3)
|
||
if len(parts) < 4: continue
|
||
|
||
domain = parts[0]
|
||
date_str = parts[1]
|
||
sender = parts[2]
|
||
subject = parts[3]
|
||
|
||
# Фильтруем откровенные пустышки по отправителю
|
||
if sender.lower() in ['no-reply', 'noreply', 'notification']:
|
||
continue
|
||
|
||
text = parse_pdf(f)
|
||
if not text.strip(): continue
|
||
|
||
meta = extract_meta_from_text(text)
|
||
|
||
is_sent = False
|
||
if sender == 'ktybdsq' or 'ktybdsq@gmail.com' in meta['from'].lower():
|
||
is_sent = True
|
||
|
||
if is_sent:
|
||
sent_emails.append({'file': f.name, 'date': date_str, 'subject': subject, 'text': text, 'meta': meta})
|
||
else:
|
||
# Проверяем, не пустышка ли это по тексту
|
||
if is_valid_reply(text):
|
||
recv_emails.append({'file': f.name, 'date': date_str, 'subject': subject, 'text': text, 'meta': meta})
|
||
|
||
print(f"Total Sent: {len(sent_emails)}")
|
||
print(f"Total Valid Replies: {len(recv_emails)}")
|
||
|
||
# Sort by date
|
||
sent_emails.sort(key=lambda x: x['date'])
|
||
recv_emails.sort(key=lambda x: x['date'])
|
||
|
||
for e in sent_emails[:2]: print("SENT:", e['date'], e['subject'])
|
||
for e in recv_emails[:2]: print("REPLY:", e['date'], e['subject'])
|
||
|