import json
import os
import string
import re
from collections import defaultdict, Counter
from datetime import datetime
from urllib.parse import urlparse
def load_json(file_path):
if not os.path.exists(file_path):
print(f"Входной файл '{file_path}' не найден.")
return None
try:
with open(file_path, 'r', encoding='utf-8') as infile:
return json.load(infile)
except json.JSONDecodeError as e:
print(f"Ошибка декодирования JSON: {e}")
return None
def save_json(data, file_path):
try:
with open(file_path, 'w', encoding='utf-8') as outfile:
json.dump(data, outfile, ensure_ascii=False, indent=2)
print(f"Данные успешно сохранены в '{file_path}'.")
except Exception as e:
print(f"Ошибка при сохранении файла: {e}")
def save_html(content, file_path):
try:
with open(file_path, 'w', encoding='utf-8') as html_file:
html_file.write(content)
print(f"HTML отчет успешно сохранен в '{file_path}'.")
except Exception as e:
print(f"Ошибка при сохранении HTML файла: {e}")
def extract_text(text_content):
if isinstance(text_content, str):
return text_content
elif isinstance(text_content, list):
text_parts = []
for item in text_content:
if isinstance(item, str):
text_parts.append(item)
elif isinstance(item, dict) and 'text' in item:
text_parts.append(item['text'])
return ''.join(text_parts)
elif isinstance(text_content, dict) and 'text' in text_content:
return text_content['text']
else:
return ''
def tokenize_text(text):
text = text.lower()
text = text.translate(str.maketrans('', '', string.punctuation))
words = text.split()
return words
user_average_lengths = {
user: round(sum(lengths) / len(lengths), 2) if lengths else 0
for user, lengths in data['user_message_lengths'].items()
}
user_avg_lengths_present = any(user_average_lengths.values())
most_common_words = data['word_counter'].most_common(50)
hours = list(data['activity_by_hour'].keys())
messages_per_hour = list(data['activity_by_hour'].values())
# Для дней недели
weekdays = list(data['activity_by_weekday'].keys())
messages_per_weekday = list(data['activity_by_weekday'].values())
weekdays, messages_per_weekday = zip(*sorted(zip(weekdays, messages_per_weekday))) if weekdays else ([], [])
weekday_labels = ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье']
weekdays = [weekday_labels[wd] for wd in weekdays]
# Для времени суток
time_of_day = list(data['activity_by_time_of_day'].keys())
messages_per_time_of_day = list(data['activity_by_time_of_day'].values())
# Проверка наличия данных для различных анализов
has_video = any(data['user_video_counts'].values())
has_voice = any(data['user_voice_counts'].values())
has_stickers = any(data['user_sticker_counts'].values())
has_citations = any(data['user_citation_counts'].values())
has_mentions = any(data['user_mentions_received'].values()) or any(data['user_mentions_made'].values())
has_hashtags = any(data['user_hashtag_counts'].values())
has_links = any(data['user_link_counts'].values())
has_long_messages = any(data['user_long_messages'].values())
has_message_edits = total_edit_count > 0
has_media_files = any(data['media_files_counter'].values())
word_freq_present = len(most_common_words) > 0
user_interactions_present = any(len(v) > 0 for v in data['user_interactions'].values())
response_times_present = any(len(v) > 0 for v in data['response_times'].values())
html = f"""
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Статистика Чата</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<style>
body {{
font-family: Arial, sans-serif;
margin: 20px;
}}
table {{
width: 100%;
border-collapse: collapse;
margin-bottom: 40px;
}}
th, td {{
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}}
th {{
background-color: #f2f2f2;
}}
h2 {{
color: #333;
}}
.chart-container {{
width: 100%;
height: 400px;
margin-bottom: 40px;
}}
.summary {{
margin-bottom: 40px;
}}
</style>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
</head>
<body>
<h1>Статистика Чата</h1>
<div class="summary">
<p><strong>Общее количество сообщений:</strong> {total_messages}</p>
</div>
<h2>Количество Сообщений на Пользователя</h2>
<table id="userMessagesTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Количество Сообщений</th>
</tr>
</thead>
<tbody>
"""
# Таблица сообщений на пользователя
for user, count in sorted(data['user_message_counts'].items(), key=lambda x: x[1], reverse=True):
html += f"""
<tr>
<td>{escape_html(user)}</td>
<td>{count}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Таблица средней длины сообщений
if user_avg_lengths_present:
html += """
<h2>Средняя Длина Сообщений на Пользователя</h2>
<table id="userAverageLengthsTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Средняя Длина Сообщения</th>
</tr>
</thead>
<tbody>
"""
for user, avg_len in sorted(user_average_lengths.items(), key=lambda x: x[1], reverse=True):
html += f"""
<tr>
<td>{escape_html(user)}</td>
<td>{avg_len}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Анализ медиафайлов
if has_media_files:
html += """
<h2>Анализ Медиафайлов</h2>
<table id="mediaFilesTable" class="display">
<thead>
<tr>
<th>Тип Медиафайла</th>
<th>Количество</th>
</tr>
</thead>
<tbody>
"""
for media_type, count in sorted(data['media_files_counter'].items(), key=lambda x: x[1], reverse=True):
html += f"""
<tr>
<td>{escape_html(media_type)}</td>
<td>{count}</td>
</tr>
"""
html += """
</tbody>
</table>
<h3>Количество Медиафайлов на Пользователя</h3>
<table id="mediaFilesPerUserTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Количество Медиафайлов</th>
</tr>
</thead>
<tbody>
"""
for user, count in sorted(data['user_media_counts'].items(), key=lambda x: x[1], reverse=True):
html += f"""
<tr>
<td>{escape_html(user)}</td>
<td>{count}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Анализ видео сообщений
if has_video:
html += """
<h2>Частота Использования Видеосообщений</h2>
<table id="videoMessagesTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Количество Видеосообщений</th>
</tr>
</thead>
<tbody>
"""
for user, count in sorted(data['user_video_counts'].items(), key=lambda x: x[1], reverse=True):
html += f"""
<tr>
<td>{escape_html(user)}</td>
<td>{count}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Анализ голосовых сообщений
if has_voice:
html += """
<h2>Частота Использования Голосовых Сообщений</h2>
<table id="voiceMessagesTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Количество Голосовых Сообщений</th>
</tr>
</thead>
<tbody>
"""
for user, count in sorted(data['user_voice_counts'].items(), key=lambda x: x[1], reverse=True):
html += f"""
<tr>
<td>{escape_html(user)}</td>
<td>{count}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Анализ стикеров
if has_stickers:
html += """
<h2>Частота Использования Стикеров</h2>
<table id="stickerMessagesTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Количество Стикеров</th>
</tr>
</thead>
<tbody>
"""
for user, count in sorted(data['user_sticker_counts'].items(), key=lambda x: x[1], reverse=True):
html += f"""
<tr>
<td>{escape_html(user)}</td>
<td>{count}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Анализ цитирования
if has_citations:
html += """
<h2>Частота Использования Цитирования</h2>
<table id="citationMessagesTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Количество Цитирований</th>
</tr>
</thead>
<tbody>
"""
for user, count in sorted(data['user_citation_counts'].items(), key=lambda x: x[1], reverse=True):
html += f"""
<tr>
<td>{escape_html(user)}</td>
<td>{count}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Анализ упоминаний
if has_mentions:
html += """
<h2>Анализ Использования Упоминаний</h2>
<h3>Кто чаще всего упоминается</h3>
<table id="mentionsReceivedTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Количество Упоминаний</th>
</tr>
</thead>
<tbody>
"""
for user, count in sorted(data['user_mentions_received'].items(), key=lambda x: x[1], reverse=True):
html += f"""
<tr>
<td>{escape_html(user)}</td>
<td>{count}</td>
</tr>
"""
html += """
</tbody>
</table>
<h3>Кто чаще всего упоминает других</h3>
<table id="mentionsMadeTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Количество Упоминаний</th>
</tr>
</thead>
<tbody>
"""
for user, count in sorted(data['user_mentions_made'].items(), key=lambda x: x[1], reverse=True):
html += f"""
<tr>
<td>{escape_html(user)}</td>
<td>{count}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Анализ хештегов
if has_hashtags:
html += """
<h2>Анализ Использования Хештегов</h2>
<h3>Топ-50 Хештегов</h3>
<table id="hashtagFrequencyTable" class="display">
<thead>
<tr>
<th>Хештег</th>
<th>Частота</th>
</tr>
</thead>
<tbody>
"""
for tag, freq in data['user_hashtag_counts'].items():
html += f"""
<tr>
<td>{escape_html(tag)}</td>
<td>{freq}</td>
</tr>
"""
html += """
</tbody>
</table>
<h3>Кто чаще всего использует хештеги</h3>
<table id="userHashtagsTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Количество Хештегов</th>
</tr>
</thead>
<tbody>
"""
for user, count in sorted(data['user_hashtags_made'].items(), key=lambda x: x[1], reverse=True):
html += f"""
<tr>
<td>{escape_html(user)}</td>
<td>{count}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Анализ ссылок
if has_links:
html += """
<h2>Анализ Использования Ссылок</h2>
<h3>Топ-Типы Ссылок</h3>
<table id="linkTypesTable" class="display">
<thead>
<tr>
<th>Тип Ссылки</th>
<th>Количество</th>
</tr>
</thead>
<tbody>
"""
for link_type, count in sorted(data['link_type_counts'].items(), key=lambda x: x[1], reverse=True):
html += f"""
<tr>
<td>{escape_html(link_type)}</td>
<td>{count}</td>
</tr>
"""
html += """
</tbody>
</table>
<h3>Кто чаще всего отправляет ссылки</h3>
<table id="userLinksTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Количество Ссылок</th>
</tr>
</thead>
<tbody>
"""
for user, count in sorted(data['user_link_counts'].items(), key=lambda x: x[1], reverse=True):
html += f"""
<tr>
<td>{escape_html(user)}</td>
<td>{count}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Анализ длинных сообщений
if has_long_messages:
html += """
<h2>Анализ Длинных Сообщений</h2>
<table id="longMessagesTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Количество Длинных Сообщений ( > 140 символов)</th>
</tr>
</thead>
<tbody>
"""
for user, count in sorted(data['user_long_messages'].items(), key=lambda x: x[1], reverse=True):
html += f"""
<tr>
<td>{escape_html(user)}</td>
<td>{count}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Анализ редактирования сообщений
if has_message_edits:
edit_percentage = (total_edit_count / total_messages) * 100 if total_messages > 0 else 0
html += f"""
<h2>Анализ Редактирования Сообщений</h2>
<p><strong>Общее количество редактирований:</strong> {total_edit_count}</p>
<p><strong>Процент редактированных сообщений:</strong> {edit_percentage:.2f}%</p>
<table id="messageEditsTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Количество Редактирований</th>
</tr>
</thead>
<tbody>
"""
for user, count in sorted(data['message_edits'].items(), key=lambda x: x[1], reverse=True):
html += f"""
<tr>
<td>{escape_html(user)}</td>
<td>{count}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Анализ временной активности
html += """
<h2>Активность Пользователей</h2>
<div class="chart-container">
<canvas id="activityByHourChart"></canvas>
</div>
<div class="chart-container">
<canvas id="activityByWeekdayChart"></canvas>
</div>
<div class="chart-container">
<canvas id="activityByTimeOfDayChart"></canvas>
</div>
"""
# Анализ длинных сообщений остаётся частью
# Частотный анализ слов
if word_freq_present:
html += """
<h2>Частотный Анализ Слов (Топ-50)</h2>
<table id="wordFrequencyTable" class="display">
<thead>
<tr>
<th>Слово</th>
<th>Частота</th>
</tr>
</thead>
<tbody>
"""
for word, freq in most_common_words:
html += f"""
<tr>
<td>{escape_html(word)}</td>
<td>{freq}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Анализ взаимодействий между пользователями
if user_interactions_present:
interactions_data = []
for user, interactions in data['user_interactions'].items():
for target_user, count in interactions.items():
interactions_data.append((user, target_user, count))
if interactions_data:
html += """
<h2>Анализ Взаимодействий между Пользователями</h2>
<table id="userInteractionsTable" class="display">
<thead>
<tr>
<th>Отправитель</th>
<th>Получатель</th>
<th>Количество</th>
</tr>
</thead>
<tbody>
"""
for sender, receiver, count in interactions_data:
html += f"""
<tr>
<td>{escape_html(sender)}</td>
<td>{escape_html(receiver)}</td>
<td>{count}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Анализ времени отклика
if response_times_present:
html += """
<h2>Анализ Времени Отклика</h2>
<table id="responseTimesTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Среднее Время Отклика (секунды)</th>
</tr>
</thead>
<tbody>
"""
for user, times in data['response_times'].items():
avg_time = round(sum(times) / len(times), 2) if times else 0
html += f"""
<tr>
<td>{escape_html(user)}</td>
<td>{avg_time}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Добавление графиков
# График активности по часам
html += """
<h2>Активность по Часам</h2>
<div class="chart-container">
<canvas id="activityByHourChart"></canvas>
</div>
"""
# График активности по дням недели
if weekdays:
html += """
<h2>Активность по Дням Недели</h2>
<div class="chart-container">
<canvas id="activityByWeekdayChart"></canvas>
</div>
"""
# График активности по времени суток
if time_of_day:
html += """
<h2>Активность по Времени Суток</h2>
<div class="chart-container">
<canvas id="activityByTimeOfDayChart"></canvas>
</div>
"""
# Добавление скриптов для графиков
html += """
<script>
// Данные для графика активности по часам
const activityByHourCtx = document.getElementById('activityByHourChart').getContext('2d');
const activityByHourChart = new Chart(activityByHourCtx, {
type: 'bar',
data: {
labels: """ + json.dumps(list(data['activity_by_hour'].keys())) + """,
datasets: [{
label: 'Количество Сообщений',
data: """ + json.dumps(list(data['activity_by_hour'].values())) + """,
backgroundColor: 'rgba(54, 162, 235, 0.6)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
},
options: {
scales: {
x: {
title: {
display: true,
text: 'Часы'
}
},
y: {
beginAtZero: true,
title: {
display: true,
text: 'Количество Сообщений'
}
}
}
}
});
// Данные для графика активности по дням недели
"""
if weekdays:
html += """
const activityByWeekdayCtx = document.getElementById('activityByWeekdayChart').getContext('2d');
const activityByWeekdayChart = new Chart(activityByWeekdayCtx, {
type: 'bar',
data: {
labels: """ + json.dumps(list(data['activity_by_weekday'].keys())) + """,
datasets: [{
label: 'Количество Сообщений',
data: """ + json.dumps(list(data['activity_by_weekday'].values())) + """,
backgroundColor: 'rgba(255, 99, 132, 0.6)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
}]
},
options: {
scales: {
x: {
title: {
display: true,
text: 'Дни Недели'
}
},
y: {
beginAtZero: true,
title: {
display: true,
text: 'Количество Сообщений'
}
}
}
}
});
"""
# Данные для графика активности по времени суток
if time_of_day:
html += """
const activityByTimeOfDayCtx = document.getElementById('activityByTimeOfDayChart').getContext('2d');
const activityByTimeOfDayChart = new Chart(activityByTimeOfDayCtx, {
type: 'bar',
data: {
labels: """ + json.dumps(list(data['activity_by_time_of_day'].keys())) + """,
datasets: [{
label: 'Количество Сообщений',
data: """ + json.dumps(list(data['activity_by_time_of_day'].values())) + """,
backgroundColor: 'rgba(153, 102, 255, 0.6)',
borderColor: 'rgba(153, 102, 255, 1)',
borderWidth: 1
}]
},
options: {
scales: {
x: {
title: {
display: true,
text: 'Время Суток'
}
},
y: {
beginAtZero: true,
title: {
display: true,
text: 'Количество Сообщений'
}
}
}
}
});
"""
html += """
// Инициализация DataTables
$(document).ready(function() {
$('#userMessagesTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
if user_avg_lengths_present:
html += """
$('#userAverageLengthsTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
if has_media_files:
html += """
$('#mediaFilesTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
$('#mediaFilesPerUserTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
if has_video:
html += """
$('#videoMessagesTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
if has_voice:
html += """
$('#voiceMessagesTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
if has_stickers:
html += """
$('#stickerMessagesTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
if has_citations:
html += """
$('#citationMessagesTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
if has_mentions:
html += """
$('#mentionsReceivedTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
$('#mentionsMadeTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
if has_hashtags:
html += """
$('#hashtagFrequencyTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
$('#userHashtagsTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
if has_links:
html += """
$('#linkTypesTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
$('#userLinksTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
if has_long_messages:
html += """
$('#longMessagesTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
if has_message_edits:
html += """
$('#messageEditsTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
if word_freq_present:
html += """
$('#wordFrequencyTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
if user_interactions_present:
html += """
$('#userInteractionsTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
if response_times_present:
html += """
$('#responseTimesTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
html += """
});
</script>
</body>
</html>
"""
return html
if name == "main":
input_file = r"C:\Users\Admin\Downloads\AyuGram Desktop\ChatExport_2024-09-23 (1)\result.json"
output_json = r"C:\Users\Admin\Downloads\AyuGram Desktop\ChatExport_2024-09-23 (1)\cleaned_result.json"
output_html = r"C:\Users\Admin\Downloads\AyuGram Desktop\ChatExport_2024-09-23 (1)\chat_statistics.html"
code
data = load_json(input_file)
if data:
analyzed_data = analyze_data(data)
save_json(analyzed_data['cleaned_messages'], output_json)
html_content = generate_html(analyzed_data)
save_html(html_content, output_html) (Статистика Чата перенеси их в данный раздел и оформи как <Общее количество сообщений:>
[Анализ Медиафайлов переведи
“voice_message- голосовое сообщение
video_message- видеосообщение
sticker-стикер
video_file- видеофайл
audio_file- аудиофайл”
Частота Использования Цитирования общая
Общее количество ссылок
Общее количество редактирований
Процент редактированных сообщений
Общее количество упоминаний])
(обьедени данные пункты в один удобный раздел
[Количество Медиафайлов на Пользователя
Частота Использования Видеосообщений
Частота Использования Голосовых Сообщений
Частота Использования Стикеров
Частота Использования Цитирования
Кто чаще всего отправляет ссылки])
Понимаю, вы хотите внести изменения в ваш скрипт для генерации HTML-отчета, чтобы объединить и отформатировать различные статистические данные согласно вашим требованиям. Я внесу необходимые изменения в функцию generate_html, чтобы:
Перенести и оформить общую статистику чата, включая общее количество сообщений, редактирований, ссылок, упоминаний и цитирований.
Перевести типы медиафайлов на русский язык.
Объединить различные медиастатистики в один удобный раздел.
Ниже представлен обновленный скрипт с внесенными изменениями:
python
import json
import os
import string
import re
from collections import defaultdict, Counter
from datetime import datetime
from urllib.parse import urlparse
def load_json(file_path):
if not os.path.exists(file_path):
print(f"Входной файл '{file_path}' не найден.")
return None
try:
with open(file_path, 'r', encoding='utf-8') as infile:
return json.load(infile)
except json.JSONDecodeError as e:
print(f"Ошибка декодирования JSON: {e}")
return None
def save_json(data, file_path):
try:
with open(file_path, 'w', encoding='utf-8') as outfile:
json.dump(data, outfile, ensure_ascii=False, indent=2)
print(f"Данные успешно сохранены в '{file_path}'.")
except Exception as e:
print(f"Ошибка при сохранении файла: {e}")
def save_html(content, file_path):
try:
with open(file_path, 'w', encoding='utf-8') as html_file:
html_file.write(content)
print(f"HTML отчет успешно сохранен в '{file_path}'.")
except Exception as e:
print(f"Ошибка при сохранении HTML файла: {e}")
def extract_text(text_content):
if isinstance(text_content, str):
return text_content
elif isinstance(text_content, list):
text_parts = []
for item in text_content:
if isinstance(item, str):
text_parts.append(item)
elif isinstance(item, dict) and 'text' in item:
text_parts.append(item['text'])
return ''.join(text_parts)
elif isinstance(text_content, dict) and 'text' in text_content:
return text_content['text']
else:
return ''
def tokenize_text(text):
text = text.lower()
text = text.translate(str.maketrans('', '', string.punctuation))
words = text.split()
return words
def get_time_of_day(hour):
if 6 <= hour < 12:
return 'Утро'
elif 12 <= hour < 18:
return 'День'
elif 18 <= hour < 24:
return 'Вечер'
else:
return 'Ночь'
def identify_hashtags(text):
return re.findall(r'#\w+', text)
def identify_mentions(text):
return re.findall(r'@\w+', text)
def identify_links(text):
# Простое регулярное выражение для поиска ссылок
return re.findall(r'(https?://[^\s]+)', text)
def get_link_type(url):
parsed_url = urlparse(url)
domain = parsed_url.netloc.lower()
if 'youtube.com' in domain or 'youtu.be' in domain:
return 'YouTube'
elif 'twitter.com' in domain:
return 'Twitter'
elif 'facebook.com' in domain:
return 'Facebook'
elif 'instagram.com' in domain:
return 'Instagram'
else:
return 'Другое'
def analyze_data(data):
cleaned_messages = []
user_message_counts = defaultdict(int)
user_video_counts = defaultdict(int)
user_voice_counts = defaultdict(int)
user_sticker_counts = defaultdict(int)
user_citation_counts = defaultdict(int)
user_mentions_received = defaultdict(int)
user_mentions_made = defaultdict(int)
user_hashtag_counts = defaultdict(int)
hashtag_counter = Counter()
user_link_counts = defaultdict(int)
link_type_counter = Counter()
activity_by_hour = defaultdict(int)
activity_by_weekday = defaultdict(int)
activity_by_time_of_day = defaultdict(int)
word_counter = Counter()
user_interactions = defaultdict(lambda: defaultdict(int))
user_reply_counts = defaultdict(int)
user_mentions_received = defaultdict(int)
user_mentions_made = defaultdict(int)
user_citations_made = defaultdict(int)
user_citations_received = defaultdict(int)
user_hashtags_made = defaultdict(int)
user_links_made = defaultdict(int)
user_long_messages = defaultdict(int)
user_message_lengths = defaultdict(list)
message_edits = defaultdict(int)
total_edit_count = 0
total_messages = 0
media_files_counter = Counter()
user_media_counts = defaultdict(int)
response_times = defaultdict(list)
russian_stopwords = set([
'и', 'в', 'во', 'не', 'что', 'он', 'на', 'я', 'с', 'со',
'как', 'а', 'то', 'все', 'она', 'так', 'его', 'но', 'да',
'ты', 'к', 'у', 'же', 'вы', 'за', 'бы', 'по', 'только', 'ее',
'мне', 'было', 'вот', 'от', 'меня', 'еще', 'нет', 'о', 'из',
'ему', 'теперь', 'когда', 'даже', 'ну', 'вдруг', 'ли', 'если',
'уже', 'или', 'ни', 'быть', 'был', 'него', 'до', 'вас', 'нибудь',
'опять', 'уж', 'вам', 'ведь', 'там', 'потом', 'себя', 'ничего',
'ей', 'может', 'они', 'тут', 'где', 'есть', 'надо', 'ней', 'для',
'мы', 'тебя', 'их', 'чем', 'была', 'сам', 'чтобы', 'без', 'будто',
'чего', 'раз', 'тоже', 'себе', 'под', 'будет', 'ж', 'тогда', 'кто',
'этот', 'того', 'потому', 'этого', 'какой', 'совсем', 'ним', 'здесь',
'этом', 'один', 'почти', 'мой', 'тем', 'чтобы', 'нее', 'кажется', 'сюда',
'туда', 'этой'
])
users = set()
# Предварительная обработка сообщений по id для быстрого поиска
messages_by_id = {msg['id']: msg for msg in data.get('messages', [])}
for message in data.get('messages', []):
total_messages += 1
user = message.get('from', 'Неизвестный пользователь')
if user != 'Неизвестный пользователь':
users.add(user)
user_message_counts[user] += 1
# Обработка медиафайлов
media_type = message.get('media_type')
if media_type:
# Перевод типов медиафайлов на русский
media_type_translations = {
'voice_message': 'голосовое сообщение',
'video_message': 'видеосообщение',
'sticker': 'стикер',
'video_file': 'видеофайл',
'audio_file': 'аудиофайл'
}
translated_media_type = media_type_translations.get(media_type, media_type)
media_files_counter[translated_media_type] += 1
user_media_counts[user] += 1
if media_type == 'video_file' or media_type == 'video_message':
user_video_counts[user] += 1
elif media_type == 'voice_message':
user_voice_counts[user] += 1
elif media_type == 'sticker':
user_sticker_counts[user] += 1
cleaned_message = {
'id': message.get('id'),
'date': message.get('date'),
'from': user,
'text': ''
}
text_content = message.get('text', '')
cleaned_text = extract_text(text_content)
cleaned_message['text'] = cleaned_text
cleaned_messages.append(cleaned_message)
message_length = len(cleaned_text)
user_message_lengths[user].append(message_length)
if message_length > 140:
user_long_messages[user] += 1
# Анализ редактирования сообщений
if 'edited' in message:
message_edits[user] += 1
total_edit_count += 1
# Обработка цитат
if 'reply_to_message_id' in message:
user_citation_counts[user] += 1
user_citations_made[user] += 1
reply_message = messages_by_id.get(message['reply_to_message_id'])
if reply_message:
reply_user = reply_message.get('from', 'Неизвестный пользователь')
user_citations_received[reply_user] += 1
# Обработка упоминаний
mentions = identify_mentions(cleaned_text)
if mentions:
user_mentions_made[user] += len(mentions)
for mention in mentions:
mentioned_user = mention[1:] # Удаляем '@'
user_mentions_received[mentioned_user] += 1
# Обработка хештегов
hashtags = identify_hashtags(cleaned_text)
if hashtags:
user_hashtags_made[user] += len(hashtags)
hashtag_counter.update([tag.lower() for tag in hashtags])
# Обработка ссылок
links = identify_links(cleaned_text)
if links:
user_links_made[user] += len(links)
for link in links:
link_type = get_link_type(link)
link_type_counter[link_type] += 1
# Анализ времени отправки
message_date = message.get('date')
if message_date:
try:
dt = datetime.fromisoformat(message_date)
hour = dt.hour
weekday = dt.weekday() # Monday = 0
time_of_day = get_time_of_day(hour)
activity_by_hour[hour] += 1
activity_by_weekday[weekday] += 1
activity_by_time_of_day[time_of_day] += 1
except ValueError:
pass
# Токенизация и подсчет слов
words = tokenize_text(cleaned_text)
words = [word for word in words if word not in russian_stopwords]
word_counter.update(words)
# Анализ взаимодействий между пользователями
if 'reply_to_message_id' in message:
reply_message_id = message['reply_to_message_id']
reply_message = messages_by_id.get(reply_message_id)
if reply_message:
reply_user = reply_message.get('from', 'Неизвестный пользователь')
if reply_user != 'Неизвестный пользователь':
user_interactions[user][reply_user] += 1
user_reply_counts[user] += 1
# Анализ времени отклика
if len(users) >= 2:
user_list = sorted(users)
for i, message in enumerate(data.get('messages', [])):
user = message.get('from', 'Неизвестный пользователь')
if user == 'Неизвестный пользователь':
continue
for j in range(i - 1, -1, -1):
prev_message = data['messages'][j]
prev_user = prev_message.get('from', 'Неизвестный пользователь')
if prev_user != 'Неизвестный пользователь' and prev_user != user:
current_date = message.get('date')
prev_date = prev_message.get('date')
if current_date and prev_date:
try:
current_dt = datetime.fromisoformat(current_date)
prev_dt = datetime.fromisoformat(prev_date)
response_time = (current_dt - prev_dt).total_seconds()
if response_time > 0:
response_times[user].append(response_time)
except ValueError:
pass
break
# Подготовка итоговых данных
analysis_results = {
'cleaned_messages': cleaned_messages,
'user_message_counts': dict(user_message_counts),
'user_video_counts': dict(user_video_counts),
'user_voice_counts': dict(user_voice_counts),
'user_sticker_counts': dict(user_sticker_counts),
'user_citation_counts': dict(user_citation_counts),
'user_mentions_received': dict(user_mentions_received),
'user_mentions_made': dict(user_mentions_made),
'user_hashtag_counts': dict(hashtag_counter),
'user_hashtags_made': dict(user_hashtags_made),
'user_link_counts': dict(user_links_made),
'link_type_counts': dict(link_type_counter),
'activity_by_hour': dict(sorted(activity_by_hour.items())),
'activity_by_weekday': dict(sorted(activity_by_weekday.items())),
'activity_by_time_of_day': dict(sorted(activity_by_time_of_day.items())),
'word_counter': word_counter,
'user_interactions': user_interactions,
'user_reply_counts': dict(user_reply_counts),
'user_mentions_received': dict(user_mentions_received),
'user_mentions_made': dict(user_mentions_made),
'user_citations_made': dict(user_citations_made),
'user_citations_received': dict(user_citations_received),
'user_hashtags_made': dict(user_hashtags_made),
'user_links_made': dict(user_links_made),
'user_long_messages': dict(user_long_messages),
'user_message_lengths': dict(user_message_lengths),
'message_edits': dict(message_edits),
'total_edit_count': total_edit_count,
'total_messages': total_messages,
'media_files_counter': dict(media_files_counter),
'user_media_counts': dict(user_media_counts),
'response_times': dict(response_times)
}
return analysis_results
def escape_html(text):
replacements = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'"
}
return ''.join(replacements.get(c, c) for c in text)
def generate_html(data):
total_messages = data['total_messages']
total_edit_count = data['total_edit_count']
total_links = sum(data['user_links_made'].values())
total_mentions = sum(data['user_mentions_made'].values())
total_quotes = sum(data['user_citation_counts'].values())
edit_percentage = (total_edit_count / total_messages) * 100 if total_messages > 0 else 0
user_average_lengths = {
user: round(sum(lengths) / len(lengths), 2) if lengths else 0
for user, lengths in data['user_message_lengths'].items()
}
user_avg_lengths_present = any(user_average_lengths.values())
most_common_words = data['word_counter'].most_common(50)
hours = list(data['activity_by_hour'].keys())
messages_per_hour = list(data['activity_by_hour'].values())
# Для дней недели
weekdays = list(data['activity_by_weekday'].keys())
messages_per_weekday = list(data['activity_by_weekday'].values())
weekdays, messages_per_weekday = zip(*sorted(zip(weekdays, messages_per_weekday))) if weekdays else ([], [])
weekday_labels = ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье']
weekdays = [weekday_labels[wd] for wd in weekdays]
# Для времени суток
time_of_day = list(data['activity_by_time_of_day'].keys())
messages_per_time_of_day = list(data['activity_by_time_of_day'].values())
# Проверка наличия данных для различных анализов
has_media_files = any(data['media_files_counter'].values())
word_freq_present = len(most_common_words) > 0
user_interactions_present = any(len(v) > 0 for v in data['user_interactions'].values())
response_times_present = any(len(v) > 0 for v in data['response_times'].values())
html = f"""
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Статистика Чата</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<style>
body {{
font-family: Arial, sans-serif;
margin: 20px;
}}
table {{
width: 100%;
border-collapse: collapse;
margin-bottom: 40px;
}}
th, td {{
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}}
th {{
background-color: #f2f2f2;
}}
h2 {{
color: #333;
}}
.chart-container {{
width: 100%;
height: 400px;
margin-bottom: 40px;
}}
.summary {{
margin-bottom: 40px;
}}
</style>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
</head>
<body>
<h1>Статистика Чата</h1>
<div class="summary">
<p><strong>Общее количество сообщений:</strong> {total_messages}</p>
<p><strong>Общее количество редактирований:</strong> {total_edit_count}</p>
<p><strong>Процент редактированных сообщений:</strong> {edit_percentage:.2f}%</p>
<p><strong>Общее количество ссылок:</strong> {total_links}</p>
<p><strong>Общее количество упоминаний:</strong> {total_mentions}</p>
<p><strong>Общее количество цитирований:</strong> {total_quotes}</p>
</div>
<h2>Анализ Медиафайлов</h2>
<table id="mediaFilesTable" class="display">
<thead>
<tr>
<th>Тип Медиафайла</th>
<th>Количество</th>
</tr>
</thead>
<tbody>
"""
# Таблица медиафайлов
for media_type, count in sorted(data['media_files_counter'].items(), key=lambda x: x[1], reverse=True):
html += f"""
<tr>
<td>{escape_html(media_type)}</td>
<td>{count}</td>
</tr>
"""
html += """
</tbody>
</table>
<h2>Медиастатистика на Пользователя и Другие Анализы</h2>
<table id="combinedMediaAndLinksTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Количество Медиафайлов</th>
<th>Видеосообщения</th>
<th>Голосовые Сообщения</th>
<th>Стикеры</th>
<th>Цитирования</th>
<th>Отправляет Ссылки</th>
</tr>
</thead>
<tbody>
"""
users_sorted = sorted(data['user_message_counts'].keys())
for user in users_sorted:
media_count = data['user_media_counts'].get(user, 0)
video_count = data['user_video_counts'].get(user, 0)
voice_count = data['user_voice_counts'].get(user, 0)
sticker_count = data['user_sticker_counts'].get(user, 0)
citation_count = data['user_citation_counts'].get(user, 0)
links_sent = data['user_links_made'].get(user, 0)
html += f"""
<tr>
<td>{escape_html(user)}</td>
<td>{media_count}</td>
<td>{video_count}</td>
<td>{voice_count}</td>
<td>{sticker_count}</td>
<td>{citation_count}</td>
<td>{links_sent}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Анализ редактирования сообщений
if total_edit_count > 0:
html += f"""
<h2>Анализ Редактирования Сообщений</h2>
<p><strong>Общее количество редактирований:</strong> {total_edit_count}</p>
<p><strong>Процент редактированных сообщений:</strong> {edit_percentage:.2f}%</p>
<table id="messageEditsTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Количество Редактирований</th>
</tr>
</thead>
<tbody>
"""
for user, count in sorted(data['message_edits'].items(), key=lambda x: x[1], reverse=True):
html += f"""
<tr>
<td>{escape_html(user)}</td>
<td>{count}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Анализ временной активности
html += """
<h2>Активность Пользователей</h2>
<div class="chart-container">
<canvas id="activityByHourChart"></canvas>
</div>
<div class="chart-container">
<canvas id="activityByWeekdayChart"></canvas>
</div>
<div class="chart-container">
<canvas id="activityByTimeOfDayChart"></canvas>
</div>
"""
# Частотный анализ слов
if word_freq_present:
html += """
<h2>Частотный Анализ Слов (Топ-50)</h2>
<table id="wordFrequencyTable" class="display">
<thead>
<tr>
<th>Слово</th>
<th>Частота</th>
</tr>
</thead>
<tbody>
"""
for word, freq in most_common_words:
html += f"""
<tr>
<td>{escape_html(word)}</td>
<td>{freq}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Анализ взаимодействий между пользователями
if user_interactions_present:
interactions_data = []
for user, interactions in data['user_interactions'].items():
for target_user, count in interactions.items():
interactions_data.append((user, target_user, count))
if interactions_data:
html += """
<h2>Анализ Взаимодействий между Пользователями</h2>
<table id="userInteractionsTable" class="display">
<thead>
<tr>
<th>Отправитель</th>
<th>Получатель</th>
<th>Количество</th>
</tr>
</thead>
<tbody>
"""
for sender, receiver, count in interactions_data:
html += f"""
<tr>
<td>{escape_html(sender)}</td>
<td>{escape_html(receiver)}</td>
<td>{count}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Анализ времени отклика
if response_times_present:
html += """
<h2>Анализ Времени Отклика</h2>
<table id="responseTimesTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Среднее Время Отклика (секунды)</th>
</tr>
</thead>
<tbody>
"""
for user, times in data['response_times'].items():
avg_time = round(sum(times) / len(times), 2) if times else 0
html += f"""
<tr>
<td>{escape_html(user)}</td>
<td>{avg_time}</td>
</tr>
"""
html += """
</tbody>
</table>
"""
# Добавление графиков
# График активности по часам
html += """
<h2>Активность по Часам</h2>
<div class="chart-container">
<canvas id="activityByHourChart"></canvas>
</div>
"""
# График активности по дням недели
if weekdays:
html += """
<h2>Активность по Дням Недели</h2>
<div class="chart-container">
<canvas id="activityByWeekdayChart"></canvas>
</div>
"""
# График активности по времени суток
if time_of_day:
html += """
<h2>Активность по Времени Суток</h2>
<div class="chart-container">
<canvas id="activityByTimeOfDayChart"></canvas>
</div>
"""
# Добавление скриптов для графиков
html += """
<script>
// Данные для графика активности по часам
const activityByHourCtx = document.getElementById('activityByHourChart').getContext('2d');
const activityByHourChart = new Chart(activityByHourCtx, {
type: 'bar',
data: {
labels: """ + json.dumps(list(data['activity_by_hour'].keys())) + """,
datasets: [{
label: 'Количество Сообщений',
data: """ + json.dumps(list(data['activity_by_hour'].values())) + """,
backgroundColor: 'rgba(54, 162, 235, 0.6)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
},
options: {
scales: {
x: {
title: {
display: true,
text: 'Часы'
}
},
y: {
beginAtZero: true,
title: {
display: true,
text: 'Количество Сообщений'
}
}
}
}
});
// Данные для графика активности по дням недели
"""
if weekdays:
html += """
const activityByWeekdayCtx = document.getElementById('activityByWeekdayChart').getContext('2d');
const activityByWeekdayChart = new Chart(activityByWeekdayCtx, {
type: 'bar',
data: {
labels: """ + json.dumps(list(data['activity_by_weekday'].keys())) + """,
datasets: [{
label: 'Количество Сообщений',
data: """ + json.dumps(list(data['activity_by_weekday'].values())) + """,
backgroundColor: 'rgba(255, 99, 132, 0.6)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
}]
},
options: {
scales: {
x: {
title: {
display: true,
text: 'Дни Недели'
}
},
y: {
beginAtZero: true,
title: {
display: true,
text: 'Количество Сообщений'
}
}
}
}
});
"""
# Данные для графика активности по времени суток
if time_of_day:
html += """
const activityByTimeOfDayCtx = document.getElementById('activityByTimeOfDayChart').getContext('2d');
const activityByTimeOfDayChart = new Chart(activityByTimeOfDayCtx, {
type: 'bar',
data: {
labels: """ + json.dumps(list(data['activity_by_time_of_day'].keys())) + """,
datasets: [{
label: 'Количество Сообщений',
data: """ + json.dumps(list(data['activity_by_time_of_day'].values())) + """,
backgroundColor: 'rgba(153, 102, 255, 0.6)',
borderColor: 'rgba(153, 102, 255, 1)',
borderWidth: 1
}]
},
options: {
scales: {
x: {
title: {
display: true,
text: 'Время Суток'
}
},
y: {
beginAtZero: true,
title: {
display: true,
text: 'Количество Сообщений'
}
}
}
}
});
"""
html += """
// Инициализация DataTables
$(document).ready(function() {
$('#mediaFilesTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
$('#combinedMediaAndLinksTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
if total_edit_count > 0:
html += """
$('#messageEditsTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
if word_freq_present:
html += """
$('#wordFrequencyTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
if user_interactions_present:
html += """
$('#userInteractionsTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
if response_times_present:
html += """
$('#responseTimesTable').DataTable({
"paging": false,
"searching": false,
"info": false
});
"""
html += """
});
</script>
</body>
</html>
"""
return html
if __name__ == "__main__":
input_file = r"C:\Users\Admin\Downloads\AyuGram Desktop\ChatExport_2024-09-23 (1)\result.json"
output_json = r"C:\Users\Admin\Downloads\AyuGram Desktop\ChatExport_2024-09-23 (1)\cleaned_result.json"
output_html = r"C:\Users\Admin\Downloads\AyuGram Desktop\ChatExport_2024-09-23 (1)\chat_statistics.html"
data = load_json(input_file)
if data:
analyzed_data = analyze_data(data)
save_json(analyzed_data['cleaned_messages'], output_json)
html_content = generate_html(analyzed_data)
save_html(html_content, output_html)
Внесенные изменения:
Перевод типов медиафайлов на русский язык:
В функции analyze_data добавлен словарь media_type_translations для перевода типов медиафайлов с английского на русский. При обработке каждого медиафайла тип заменяется на соответствующий русский эквивалент.
В функции generate_html секция summary расширена, чтобы включать общее количество сообщений, редактирований, ссылок, упоминаний и цитирований.
html
<div class="summary">
<p><strong>Общее количество сообщений:</strong> {total_messages}</p>
<p><strong>Общее количество редактирований:</strong> {total_edit_count}</p>
<p><strong>Процент редактированных сообщений:</strong> {edit_percentage:.2f}%</p>
<p><strong>Общее количество ссылок:</strong> {total_links}</p>
<p><strong>Общее количество упоминаний:</strong> {total_mentions}</p>
<p><strong>Общее количество цитирований:</strong> {total_quotes}</p>
</div>
Объединение медиастатистики и других анализов в один раздел:
Создана новая таблица combinedMediaAndLinksTable, которая объединяет информацию о количестве медиафайлов, видеосообщениях, голосовых сообщениях, стикерах, цитированиях и отправке ссылок по каждому пользователю.
html
Дополнительные рекомендации:
Добавление обработчика отсутствующих типов медиафайлов:
Если есть типы медиафайлов, не указанные в словаре media_type_translations, они будут отображаться как есть. При необходимости можно расширить словарь переводов.
Оптимизация периода анализа времени отклика:
В текущей реализации анализируется время отклика между сообщениями. Можно добавить фильтры или улучшить точность данного анализа.
Улучшение визуализации:
Можно добавить дополнительные графики или диаграммы для более наглядного представления данных.
Теперь ваш HTML-отчет будет содержать более структурированную и понятную информацию, соответствующую вашим требованиям. Если у вас возникнут дополнительные вопросы или потребуется дальнейшая помощь, пожалуйста, дайте знать!