import json
import os
import string
import re
from collections import defaultdict, Counter
from datetime import datetime
from urllib.parse import urlparse
import html # Для безопасного экранирования HTML
import emoji
from wordcloud import WordCloud
from textblob import TextBlob
import gensim
from gensim import corpora
import nltk
from nltk.stem import WordNetLemmatizer
import networkx as nx
import plotly.graph_objs as go
import matplotlib # Добавлено для устранения сообщения о бекенде
matplotlib.use('Agg') # Установить неинтерактивный бекенд
Для загрузки данных NLTK
nltk.download('punkt')
nltk.download('wordnet')
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_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
edit_percentage = (total_edit_count / total_messages) * 100 if total_messages > 0 else 0
# Топ-50 слов
most_common_words = sorted(data['word_counter'].items(), key=lambda x: x[1], reverse=True)[:50]
# Для дней недели
weekdays_num = sorted(map(int, data['activity_by_weekday'].keys()), key=int)
messages_per_weekday = [data['activity_by_weekday'].get(wd, 0) for wd in weekdays_num]
weekday_labels = ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье']
weekdays_labels = [weekday_labels[wd] for wd in weekdays_num if 0 <= wd < 7]
# Для времени суток
time_of_day_labels = list(data['activity_by_time_of_day'].keys())
messages_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 = len(data['user_interactions']) > 0
response_times_present = any(len(v) > 0 for v in data['response_times'].values())
forwarded_messages_present = any(count > 0 for count in data['forwarded_from_counter'].values())
topics_present = len(data['topics']) > 0
average_size_present = average_message_size > 0
average_size_per_user_present = len(data.get('average_message_size_per_user', {})) > 0
month_activity_present = len(data.get('activity_by_month', {})) > 0
year_activity_present = len(data.get('activity_by_year', {})) > 0
# Определение необходимости генерации графиков по месяцам и годам
generate_monthly_chart = data['chat_duration_months'] > 1
generate_yearly_chart = data['chat_duration_years'] > 1
html_content = 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;
}}
.word-cloud {{
max-width: 100%;
height: auto;
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>
"""
if average_size_present:
html_content += f"""
<p><strong>Средний размер сообщений:</strong> {average_message_size} символов</p>
"""
# Добавление количества сообщений по пользователям
if average_size_per_user_present:
html_content += """
<h2>Количество сообщений по пользователям</h2>
<table id="userMessageCountsTable" 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_content += f"""
<tr>
<td>{html.escape(user)}</td>
<td>{count}</td>
</tr>
"""
html_content += """
</tbody>
</table>
"""
# Добавление среднего размера сообщений по пользователям
if average_size_per_user_present:
html_content += """
<h2>Средний размер сообщений по пользователям</h2>
<table id="averageMessageSizeTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Средний размер сообщения (символы)</th>
</tr>
</thead>
<tbody>
"""
for user, avg_size in sorted(data['average_message_size_per_user'].items(), key=lambda x: x[1], reverse=True):
html_content += f"""
<tr>
<td>{html.escape(user)}</td>
<td>{avg_size}</td>
</tr>
"""
html_content += """
</tbody>
</table>
"""
# Анализ Медиафайлов
html_content += f"""
<h2>Анализ Медиафайлов</h2>
<p><strong>Голосовые сообщения:</strong> {data['media_files_counter'].get('Голосовое сообщение', 0)}</p>
<p><strong>Видеосообщения:</strong> {data['media_files_counter'].get('Видеосообщение', 0)}</p>
<p><strong>Аудиофайлы:</strong> {data['media_files_counter'].get('Аудиофайл', 0)}</p>
<p><strong>Видеофайлы:</strong> {data['media_files_counter'].get('Видеофайл', 0)}</p>
<p><strong>Стикеры:</strong> {data['media_files_counter'].get('Стикер', 0)}</p>
"""
# Таблица пересланных сообщений
if forwarded_messages_present:
html_content += f"""
<h2>Анализ Пересланных Сообщений</h2>
<table id="forwardedMessagesTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Количество Пересланных Сообщений</th>
</tr>
</thead>
<tbody>
"""
for user, count in sorted(data.get('user_forwarded_counts', {}).items(), key=lambda x: x[1], reverse=True):
html_content += f"""
<tr>
<td>{html.escape(user)}</td>
<td>{count}</td>
</tr>
"""
html_content += """
</tbody>
</table>
<h3>Источник Пересылок</h3>
<table id="forwardedFromTable" class="display">
<thead>
<tr>
<th>От кого пересылают</th>
<th>Количество Пересланных Сообщений</th>
</tr>
</thead>
<tbody>
"""
for user, count in sorted(data['forwarded_from_counter'].items(), key=lambda x: x[1], reverse=True):
html_content += f"""
<tr>
<td>{html.escape(user)}</td>
<td>{count}</td>
</tr>
"""
html_content += """
</tbody>
</table>
"""
# Таблица медиастатистики по пользователям
html_content += f"""
<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_content += f"""
<tr>
<td>{html.escape(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_content += """
</tbody>
</table>
"""
# Анализ редактирования сообщений
if total_edit_count > 0:
html_content += f"""
<h2>Анализ Редактирования Сообщений</h2>
<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_content += f"""
<tr>
<td>{html.escape(user)}</td>
<td>{count}</td>
</tr>
"""
html_content += """
</tbody>
</table>
"""
# Анализ временной активности
html_content += """
<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_content += """
<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_content += f"""
<tr>
<td>{html.escape(word)}</td>
<td>{freq}</td>
</tr>
"""
html_content += """
</tbody>
</table>
"""
# Облако слов
word_cloud_full_path = os.path.join(base_dir, data['word_cloud_path'])
if word_freq_present and os.path.exists(word_cloud_full_path):
html_content += f"""
<h2>Облако Слов</h2>
<img src="{data['word_cloud_path']}" alt="Облако Слов" class="word-cloud">
"""
# Частотный анализ эмодзи
if len(data['emoji_counter']) > 0:
most_common_emojis = sorted(data['emoji_counter'].items(), key=lambda x: x[1], reverse=True)[:50]
html_content += """
<h2>Частотный Анализ Эмодзи (Топ-50)</h2>
<table id="emojiFrequencyTable" class="display">
<thead>
<tr>
<th>Эмодзи</th>
<th>Частота</th>
</tr>
</thead>
<tbody>
"""
for emj, freq in most_common_emojis:
html_content += f"""
<tr>
<td>{emj}</td>
<td>{freq}</td>
</tr>
"""
html_content += """
</tbody>
</table>
"""
# Анализ взаимодействий между пользователями
if user_interactions_present:
interactions_data = []
for user, interactions in data['user_interactions'].items():
for target, count in interactions.items():
interactions_data.append((user, target, count))
if interactions_data:
html_content += """
<h2>Анализ Взаимодействий между Пользователями</h2>
<div>
""" + data['interaction_graph_html'] + """
</div>
<table id="userInteractionsTable" class="display">
<thead>
<tr>
<th>Отправитель</th>
<th>Получатель</th>
<th>Количество</th>
</tr>
</thead>
<tbody>
"""
for sender, receiver, count in interactions_data:
html_content += f"""
<tr>
<td>{html.escape(sender)}</td>
<td>{html.escape(receiver)}</td>
<td>{count}</td>
</tr>
"""
html_content += """
</tbody>
</table>
"""
# Анализ времени отклика
if response_times_present:
html_content += """
<h2>Анализ Времени Отклика</h2>
<table id="responseTimesTable" class="display">
<thead>
<tr>
<th>Пользователь</th>
<th>Среднее Время Отклика (секунды)</th>
<th>Медиана Времени Отклика (секунды)</th>
<th>Стандартное Отлонение (секунды)</th>
</tr>
</thead>
<tbody>
"""
for user, times in data['response_times'].items():
if times:
average = round(sum(times) / len(times), 2)
sorted_times = sorted(times)
median = round(sorted_times[len(sorted_times) // 2], 2) if len(sorted_times) > 0 else 0
variance = sum((x - average) ** 2 for x in times) / len(times) if len(times) > 0 else 0
std_dev = round(variance ** 0.5, 2)
html_content += f"""
<tr>
<td>{html.escape(user)}</td>
<td>{average}</td>
<td>{median}</td>
<td>{std_dev}</td>
</tr>
"""
else:
html_content += f"""
<tr>
<td>{html.escape(user)}</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
"""
html_content += """
</tbody>
</table>
"""
# Тематическое моделирование
if topics_present:
html_content += f"""
<h2>Тематическое Моделирование</h2>
<table id="topicsTable" class="display">
<thead>
<tr>
<th>Тема</th>
<th>Ключевые Слова</th>
</tr>
</thead>
<tbody>
"""
for idx, topic in data['topics']:
html_content += f"""
<tr>
<td>{idx}</td>
<td>{html.escape(topic)}</td>
</tr>
"""
html_content += """
</tbody>
</table>
"""
# Добавление графиков
# График активности по часам
# График активности по дням недели
# График активности по времени суток
# График активности по месяцам (условно)
# График активности по годам (условно)
# Подготовка данных для графиков по месяцам и годам
months = sorted(data['activity_by_month'].keys())
messages_per_month = [data['activity_by_month'][month] for month in months]
years = sorted(data['activity_by_year'].keys())
messages_per_year = [data['activity_by_year'][year] for year in years]
# Генерация скриптов для графиков
js_scripts = f"""
<script>
// Данные для графика активности по часам
const activityByHourCtx = document.getElementById('activityByHourChart').getContext('2d');
const activityByHourChart = new Chart(activityByHourCtx, {{
type: 'bar',
data: {{
labels: {json.dumps(labels_hours)},
datasets: [{{
label: 'Количество Сообщений',
data: {json.dumps(messages_per_hour)},
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: 'Количество Сообщений'
}}
}}
}}
}}
}});
// Данные для графика активности по дням недели
const activityByWeekdayCtx = document.getElementById('activityByWeekdayChart').getContext('2d');
const activityByWeekdayChart = new Chart(activityByWeekdayCtx, {{
type: 'bar',
data: {{
labels: {json.dumps(labels_weekdays)},
datasets: [{{
label: 'Количество Сообщений',
data: {json.dumps(messages_per_weekday)},
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: 'Количество Сообщений'
}}
}}
}}
}}
}});
// Данные для графика активности по времени суток
const activityByTimeOfDayCtx = document.getElementById('activityByTimeOfDayChart').getContext('2d');
const activityByTimeOfDayChart = new Chart(activityByTimeOfDayCtx, {{
type: 'bar',
data: {{
labels: {json.dumps(labels_time_of_day)},
datasets: [{{
label: 'Количество Сообщений',
data: {json.dumps(messages_time_of_day)},
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: 'Количество Сообщений'
}}
}}
}}
}}
}});
"""
# Добавление графика по месяцам, если нужно
if generate_monthly_chart:
js_monthly = f"""
// Данные для графика активности по месяцам
const activityByMonthCtx = document.getElementById('activityByMonthChart').getContext('2d');
const activityByMonthChart = new Chart(activityByMonthCtx, {{
type: 'bar',
data: {{
labels: {json.dumps(months)},
datasets: [{{
label: 'Количество Сообщений',
data: {json.dumps(messages_per_month)},
backgroundColor: 'rgba(75, 192, 192, 0.6)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
}}]
}},
options: {{
scales: {{
x: {{
title: {{
display: true,
text: 'Месяцы'
}},
ticks: {{
maxRotation: 90,
minRotation: 45
}}
}},
y: {{
beginAtZero: true,
title: {{
display: true,
text: 'Количество Сообщений'
}}
}}
}},
responsive: true,
maintainAspectRatio: false
}}
}});
"""
js_scripts += js_monthly
# Добавление графика по годам, если нужно
if generate_yearly_chart:
js_yearly = f"""
// Данные для графика активности по годам
const activityByYearCtx = document.getElementById('activityByYearChart').getContext('2d');
const activityByYearChart = new Chart(activityByYearCtx, {{
type: 'bar',
data: {{
labels: {json.dumps(years)},
datasets: [{{
label: 'Количество Сообщений',
data: {json.dumps(messages_per_year)},
backgroundColor: 'rgba(255, 206, 86, 0.6)',
borderColor: 'rgba(255, 206, 86, 1)',
borderWidth: 1
}}]
}},
options: {{
scales: {{
x: {{
title: {{
display: true,
text: 'Годы'
}}
}},
y: {{
beginAtZero: true,
title: {{
display: true,
text: 'Количество Сообщений'
}}
}}
}},
responsive: true,
maintainAspectRatio: false
}}
}});
"""
js_scripts += js_yearly
# Инициализация DataTables
js_scripts += """
// Инициализация DataTables
$(document).ready(function() {
$('#userMessageCountsTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
$('#averageMessageSizeTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
"""
if forwarded_messages_present:
js_scripts += """
$('#forwardedMessagesTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
$('#forwardedFromTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
"""
if total_edit_count > 0:
js_scripts += """
$('#messageEditsTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
"""
if word_freq_present:
js_scripts += """
$('#wordFrequencyTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
"""
if len(data['emoji_counter']) > 0:
js_scripts += """
$('#emojiFrequencyTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
"""
if user_interactions_present:
js_scripts += """
$('#userInteractionsTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
"""
if response_times_present:
js_scripts += """
$('#responseTimesTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
"""
if topics_present:
js_scripts += """
$('#topicsTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
"""
js_scripts += """
});
</script>
"""
# Добавление JavaScript-кода в конец HTML
html_content += js_scripts
html_content += """
</body>
</html>
"""
return html_content
if name == "main":
# Замените путь ниже на путь к вашей директории
base_dir = r"C:\Users\Admin\Downloads\AyuGram Desktop\ChatExport_2024-09-23 (7)"
input_file = os.path.join(base_dir, "result.json")
# output_json = os.path.join(base_dir, "cleaned_result.json") # Удалено
output_html = os.path.join(base_dir, "chat_statistics.html")
Предупреждение (активно) reportUndefinedVariable "labels_hours" is not defined c:\Users\Admin\source\repos\JSONAnalytics\JSONAnalytics\JSONAnalytics.py 1023
Предупреждение (активно) reportUndefinedVariable "messages_per_hour" is not defined c:\Users\Admin\source\repos\JSONAnalytics\JSONAnalytics\JSONAnalytics.py 1026
Предупреждение (активно) reportUndefinedVariable "labels_weekdays" is not defined c:\Users\Admin\source\repos\JSONAnalytics\JSONAnalytics\JSONAnalytics.py 1056
Предупреждение (активно) reportUndefinedVariable "labels_time_of_day" is not defined c:\Users\Admin\source\repos\JSONAnalytics\JSONAnalytics\JSONAnalytics.py 1089
Похоже, у вас возникает проблема с неопределёнными переменными labels_hours, messages_per_hour, labels_weekdays и labels_time_of_day. Это происходит потому, что эти переменные не были определены перед их использованием в JavaScript-коде внутри функции generate_html. Давайте рассмотрим, как можно исправить эту проблему.
Шаги по исправлению
Определение необходимых переменных:
Перед использованием переменных в JavaScript-коде, необходимо убедиться, что они определены и инициализированы в Python. В вашем случае, вам нужно определить:
labels_hours и messages_per_hour для графика активности по часам.
labels_weekdays для графика активности по дням недели.
Обновление функции generate_html:
Внутри функции generate_html, добавьте определения этих переменных перед созданием JavaScript-кода.
Обновленный код функции generate_html
Ниже представлен обновленный фрагмент функции generate_html, который включает определения необходимых переменных:
python
def generate_html(data, base_dir):
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())
average_message_size = data.get('average_message_size', 0)
edit_percentage = (total_edit_count / total_messages) * 100 if total_messages > 0 else 0
# Топ-50 слов
most_common_words = sorted(data['word_counter'].items(), key=lambda x: x[1], reverse=True)[:50]
# Для дней недели
weekdays_num = sorted(map(int, data['activity_by_weekday'].keys()), key=int)
messages_per_weekday = [data['activity_by_weekday'].get(wd, 0) for wd in weekdays_num]
weekday_labels = ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье']
weekdays_labels = [weekday_labels[wd] for wd in weekdays_num if 0 <= wd < 7]
# Для времени суток
time_of_day_labels = list(data['activity_by_time_of_day'].keys())
messages_time_of_day = list(data['activity_by_time_of_day'].values())
# **Новые определения переменных:**
# Для часов
labels_hours = [str(h) for h in range(24)]
messages_per_hour = [data['activity_by_hour'].get(h, 0) for h in range(24)]
# Для дней недели
labels_weekdays = weekdays_labels
# Для времени суток
labels_time_of_day = time_of_day_labels
# Подготовка других данных
# ... (остальной код генерации HTML)
# Подготовка данных для графиков по месяцам и годам
months = sorted(data['activity_by_month'].keys())
messages_per_month = [data['activity_by_month'][month] for month in months]
years = sorted(data['activity_by_year'].keys())
messages_per_year = [data['activity_by_year'][year] for year in years]
# Генерация скриптов для графиков
js_scripts = f"""
<script>
// Данные для графика активности по часам
const activityByHourCtx = document.getElementById('activityByHourChart').getContext('2d');
const activityByHourChart = new Chart(activityByHourCtx, {{
type: 'bar',
data: {{
labels: {json.dumps(labels_hours)},
datasets: [{{
label: 'Количество Сообщений',
data: {json.dumps(messages_per_hour)},
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: 'Количество Сообщений'
}}
}}
}}
}}
}});
// Данные для графика активности по дням недели
const activityByWeekdayCtx = document.getElementById('activityByWeekdayChart').getContext('2d');
const activityByWeekdayChart = new Chart(activityByWeekdayCtx, {{
type: 'bar',
data: {{
labels: {json.dumps(labels_weekdays)},
datasets: [{{
label: 'Количество Сообщений',
data: {json.dumps(messages_per_weekday)},
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: 'Количество Сообщений'
}}
}}
}}
}}
}});
// Данные для графика активности по времени суток
const activityByTimeOfDayCtx = document.getElementById('activityByTimeOfDayChart').getContext('2d');
const activityByTimeOfDayChart = new Chart(activityByTimeOfDayCtx, {{
type: 'bar',
data: {{
labels: {json.dumps(labels_time_of_day)},
datasets: [{{
label: 'Количество Сообщений',
data: {json.dumps(messages_time_of_day)},
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: 'Количество Сообщений'
}}
}}
}}
}}
}});
"""
# Добавление графика по месяцам, если нужно
if generate_monthly_chart:
js_monthly = f"""
// Данные для графика активности по месяцам
const activityByMonthCtx = document.getElementById('activityByMonthChart').getContext('2d');
const activityByMonthChart = new Chart(activityByMonthCtx, {{
type: 'bar',
data: {{
labels: {json.dumps(months)},
datasets: [{{
label: 'Количество Сообщений',
data: {json.dumps(messages_per_month)},
backgroundColor: 'rgba(75, 192, 192, 0.6)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
}}]
}},
options: {{
scales: {{
x: {{
title: {{
display: true,
text: 'Месяцы'
}},
ticks: {{
maxRotation: 90,
minRotation: 45
}}
}},
y: {{
beginAtZero: true,
title: {{
display: true,
text: 'Количество Сообщений'
}}
}}
}},
responsive: true,
maintainAspectRatio: false
}}
}});
"""
js_scripts += js_monthly
# Добавление графика по годам, если нужно
if generate_yearly_chart:
js_yearly = f"""
// Данные для графика активности по годам
const activityByYearCtx = document.getElementById('activityByYearChart').getContext('2d');
const activityByYearChart = new Chart(activityByYearCtx, {{
type: 'bar',
data: {{
labels: {json.dumps(years)},
datasets: [{{
label: 'Количество Сообщений',
data: {json.dumps(messages_per_year)},
backgroundColor: 'rgba(255, 206, 86, 0.6)',
borderColor: 'rgba(255, 206, 86, 1)',
borderWidth: 1
}}]
}},
options: {{
scales: {{
x: {{
title: {{
display: true,
text: 'Годы'
}}
}},
y: {{
beginAtZero: true,
title: {{
display: true,
text: 'Количество Сообщений'
}}
}}
}},
responsive: true,
maintainAspectRatio: false
}}
}});
"""
js_scripts += js_yearly
# Инициализация DataTables
js_scripts += """
// Инициализация DataTables
$(document).ready(function() {
$('#userMessageCountsTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
$('#averageMessageSizeTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
"""
if forwarded_messages_present:
js_scripts += """
$('#forwardedMessagesTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
$('#forwardedFromTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
"""
if total_edit_count > 0:
js_scripts += """
$('#messageEditsTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
"""
if word_freq_present:
js_scripts += """
$('#wordFrequencyTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
"""
if len(data['emoji_counter']) > 0:
js_scripts += """
$('#emojiFrequencyTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
"""
if user_interactions_present:
js_scripts += """
$('#userInteractionsTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
"""
if response_times_present:
js_scripts += """
$('#responseTimesTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
"""
if topics_present:
js_scripts += """
$('#topicsTable').DataTable({
"paging": true,
"searching": true,
"info": true
});
"""
js_scripts += """
});
</script>
"""
# Добавление JavaScript-кода в конец HTML
html_content += js_scripts
html_content += """
</body>
</html>
"""
return html_content
Пояснения к изменениям
Определение labels_hours и messages_per_hour:
python
labels_hours = [str(h) for h in range(24)]
messages_per_hour = [data['activity_by_hour'].get(h, 0) for h in range(24)]
labels_hours создаёт список из строковых представлений часов от 0 до 23.
messages_per_hour собирает количество сообщений для каждого часа. Здесь предполагается, что ключи в data['activity_by_hour'] являются целыми числами от 0 до 23. Если ключи представлены строками, измените h на str(h) в get.
Определение labels_weekdays:
python
labels_weekdays = weekdays_labels
Это связывает ранее созданный список weekdays_labels с переменной labels_weekdays, которая используется в JavaScript-коде.
Определение labels_time_of_day:
python
labels_time_of_day = time_of_day_labels
Это связывает список time_of_day_labels с переменной labels_time_of_day для использования в графике активности по времени суток.
Обновление JavaScript-кода:
Внутри js_scripts, замените отсутствующие переменные на определённые выше переменные Python. Используйте json.dumps для передачи списков в формате JSON в JavaScript.
Дополнительные рекомендации
Проверка типов данных:
Убедитесь, что типы данных ключей в словарях data['activity_by_hour'], data['activity_by_weekday'] и других соответствуют тем, которые используются при доступе через get. Например, если ключи строковые, применяйте str(h).
Обработка отсутствующих данных:
При использовании метода get, устанавливайте значение по умолчанию (например, 0), чтобы избежать ошибок при отсутствии данных.
Локализация и форматирование:
Убедитесь, что все подписи и метки на графиках соответствуют необходимому языку и формату.
Итог
После внесения этих изменений, ваш скрипт должен корректно определять все необходимые переменные, и предупреждения об неопределённых переменных исчезнут. Убедитесь, что все остальные части кода также правильно взаимодействуют друг с другом и корректно обрабатывают данные.
Если у вас возникнут дополнительные вопросы или проблемы, не стесняйтесь обращаться за помощью!