feat(core): initial commit unified architecture (scud_ai v2.5 with modular web_api)
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Добавляем корень проекта в путь поиска модулей Python
|
||||
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from core.database import get_connection
|
||||
|
||||
rule_text = (
|
||||
"Сотрудники, присутствующие в 1С:ЗУП, но отсутствующие в СКУД Орион Pro, "
|
||||
"являются аномалией синхронизации профилей. ИИ должен запрашивать у СБ статус выдачи пропуска."
|
||||
)
|
||||
|
||||
with get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("INSERT OR IGNORE INTO ai_knowledge_base (rule_text) VALUES (?)", (rule_text,))
|
||||
conn.commit()
|
||||
|
||||
print("✓ Правило успешно внесено в SQLite БД!")
|
||||
@@ -0,0 +1,348 @@
|
||||
import os
|
||||
import sys
|
||||
import argparse
|
||||
import sqlite3
|
||||
import pandas as pd
|
||||
from datetime import datetime
|
||||
|
||||
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from config import DATA_DIR, DATE_TODAY, OUTPUT_DIR
|
||||
from core.database import (
|
||||
get_connection,
|
||||
get_available_snapshots,
|
||||
get_all_rules_from_db,
|
||||
load_scud_from_db_by_snapshot,
|
||||
get_latest_snapshot_time
|
||||
)
|
||||
|
||||
DB_PATH = os.path.join(DATA_DIR, "scud_orion_ai.db")
|
||||
|
||||
|
||||
def print_stats():
|
||||
"""Выводит общую статистику по записям в таблицах БД."""
|
||||
print("\n" + "=" * 60)
|
||||
print("📊 СТАТИСТИКА БАЗЫ ДАННЫХ SQLITE (scud_orion_ai.db):")
|
||||
print("=" * 60)
|
||||
with get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
tables = ['scud_logs', 'zup_staff', 'zup_absences', 'anomalies_history', 'ai_knowledge_base']
|
||||
for t in tables:
|
||||
cursor.execute(f"SELECT COUNT(*) FROM {t}")
|
||||
cnt = cursor.fetchone()[0]
|
||||
print(f" • Таблица [{t:<18}]: {cnt:>6} записей")
|
||||
print("=" * 60 + "\n")
|
||||
|
||||
|
||||
def print_snapshots_list(date_str=None):
|
||||
"""Выводит реестр снапшотов с отображением даты и точного времени среза."""
|
||||
rows = get_available_snapshots(date_str)
|
||||
|
||||
print("\n" + "=" * 105)
|
||||
print(f"📸 РЕЕСТР СОХРАНЕННЫХ СНАПШОТОВ (СВЕРХУ СВЕЖИЕ) {'ЗА ЛОГИ ' + date_str if date_str else ''}:")
|
||||
print("=" * 105)
|
||||
|
||||
header = f"{'ID снапшота':<16} | {'Дата снапшота (создания)':<24} | {'Дата и время среза':<20} | {'Записей':<8}"
|
||||
print(header)
|
||||
print("-" * 105)
|
||||
|
||||
if not rows:
|
||||
print("Снапшотов пока нет.")
|
||||
print("=" * 105 + "\n")
|
||||
return
|
||||
|
||||
def snapshot_sort_key(row):
|
||||
snap_id = row[0] or ""
|
||||
snap_time = row[2] or ""
|
||||
|
||||
seq_num = 0
|
||||
if "-" in snap_id:
|
||||
parts = snap_id.replace("Y", "").split("-")
|
||||
if len(parts) > 1 and parts[1].isdigit():
|
||||
seq_num = int(parts[1])
|
||||
|
||||
return (snap_time, seq_num)
|
||||
|
||||
sorted_rows = sorted(rows, key=snapshot_sort_key, reverse=True)
|
||||
|
||||
for r in sorted_rows:
|
||||
snap_id = r[0] if r[0] else '----------'
|
||||
log_date = r[1] if r[1] else '—'
|
||||
snap_time = r[2] if r[2] else '—'
|
||||
count = r[3]
|
||||
|
||||
time_part = "—"
|
||||
if snap_time and " " in snap_time:
|
||||
time_part = snap_time.split(" ")[1]
|
||||
|
||||
slice_datetime_str = f"{log_date} {time_part}" if time_part != "—" else log_date
|
||||
|
||||
if not snap_id.startswith("Y"):
|
||||
formatted_snap_id = f" {snap_id}"
|
||||
else:
|
||||
formatted_snap_id = snap_id
|
||||
|
||||
print(f"{formatted_snap_id:<16} | {snap_time:<24} | {slice_datetime_str:<20} | {count:<8}")
|
||||
|
||||
print("=" * 105 + "\n")
|
||||
|
||||
|
||||
def delete_snapshot_by_id(snapshot_id: str):
|
||||
"""Удаляет конкретный снапшот из таблицы scud_logs по его ID."""
|
||||
with get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("DELETE FROM scud_logs WHERE snapshot_id = ?", (snapshot_id,))
|
||||
deleted_count = cursor.rowcount
|
||||
conn.commit()
|
||||
print(f"\n[✓] Успешно удален снапшот [{snapshot_id}]. Удалено строк: {deleted_count}\n")
|
||||
return deleted_count
|
||||
|
||||
|
||||
def delete_snapshots_by_date(date_str: str):
|
||||
"""Удаляет все снапшоты за указанную дату (например, '04.08.2026')."""
|
||||
with get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("DELETE FROM scud_logs WHERE log_date = ? OR snapshot_id LIKE ?", (date_str, f"%{date_str.replace('.', '')}%"))
|
||||
deleted_count = cursor.rowcount
|
||||
conn.commit()
|
||||
print(f"\n[✓] Успешно удалены все снапшоты за дату [{date_str}]. Удалено строк: {deleted_count}\n")
|
||||
return deleted_count
|
||||
|
||||
|
||||
def inspect_scud(snapshot_id=None, date_str=None, export_xlsx=None):
|
||||
"""Инспектирует логи СКУД за выбранный снапшот или дату и опционально сохраняет XLSX."""
|
||||
target_date = date_str if date_str else DATE_TODAY
|
||||
|
||||
print("\n" + "=" * 90)
|
||||
if snapshot_id:
|
||||
print(f"🔍 ИНСПЕКЦИЯ СКУД ПО СНАПШОТУ [{snapshot_id}] (Дата: {target_date}):")
|
||||
else:
|
||||
print(f"🔍 ИНСПЕКЦИЯ СКУД ЗА ТЕКУЩУЮ ДАТУ [{target_date}] (ПОСЛЕДНИЙ СРЕЗ):")
|
||||
print("=" * 90)
|
||||
|
||||
df = load_scud_from_db_by_snapshot(target_date, snapshot_param=snapshot_id)
|
||||
|
||||
if df.empty:
|
||||
print(f"Записи СКУД не найдены.")
|
||||
print("=" * 90 + "\n")
|
||||
return
|
||||
|
||||
total = len(df)
|
||||
present_cnt = len(df[df['Пришел'] == True]) if 'Пришел' in df.columns else 0
|
||||
absent_cnt = total - present_cnt
|
||||
|
||||
print(f"Всего записей: {total} | Пришли: {present_cnt} | Не пришли: {absent_cnt}")
|
||||
print("-" * 90)
|
||||
|
||||
cols_to_show = ['fio', 'department', 'position', 'time_in', 'first_activity', 'time_out', 'is_present', 'anomaly_flag', 'snapshot_id']
|
||||
existing_cols = [c for c in cols_to_show if c in df.columns]
|
||||
|
||||
print(df[existing_cols].head(30).to_string(index=False))
|
||||
if len(df) > 30:
|
||||
print(f"\n... и ещё {len(df) - 30} строк.")
|
||||
|
||||
if export_xlsx:
|
||||
out_path = export_xlsx if export_xlsx.endswith('.xlsx') else f"{export_xlsx}.xlsx"
|
||||
if not os.path.isabs(out_path):
|
||||
out_path = os.path.join(OUTPUT_DIR, out_path)
|
||||
|
||||
df.to_excel(out_path, index=False)
|
||||
print("\n" + "*" * 90)
|
||||
print(f"[✓] УСПЕШНЫЙ ЭКСПОРТ ДЕБАГ-ФАЙЛА В EXCEL: {out_path}")
|
||||
print("*" * 90)
|
||||
|
||||
print("=" * 90 + "\n")
|
||||
|
||||
|
||||
def print_absences(date_str=None):
|
||||
"""Выводит список официально отсутствующих сотрудников из 1С:ЗУП за выбранный день."""
|
||||
target_date = date_str if date_str else DATE_TODAY
|
||||
print("\n" + "=" * 90)
|
||||
print(f"📋 ОФИЦИАЛЬНЫЕ ОТСУТСТВИЯ ИЗ 1С:ЗУП ЗА ДАТУ [{target_date}]:")
|
||||
print("=" * 90)
|
||||
|
||||
with get_connection() as conn:
|
||||
df = pd.read_sql_query(
|
||||
"SELECT fio as 'ФИО', absence_type as 'Причина отсутствия 1С' FROM zup_absences WHERE absence_date = ? ORDER BY absence_type, fio",
|
||||
conn,
|
||||
params=(target_date,)
|
||||
)
|
||||
|
||||
if df.empty:
|
||||
print(f"Записи об отсутствиях 1С за {target_date} в базе не найдены.")
|
||||
else:
|
||||
print(f"Всего зафиксировано документов 1С: {len(df)}")
|
||||
print("-" * 90)
|
||||
print(df.to_string(index=False))
|
||||
|
||||
print("=" * 90 + "\n")
|
||||
|
||||
|
||||
def print_anomalies():
|
||||
"""Выводит список аномалий СКУД из БД."""
|
||||
print("\n" + "=" * 80)
|
||||
print("🚨 ИСТОРИЯ НАЙДЕННЫХ АНОМАЛИЙ СКУД ⟷ 1С:")
|
||||
print("=" * 80)
|
||||
with get_connection() as conn:
|
||||
df = pd.read_sql_query("SELECT anomaly_date, fio, anomaly_type, details FROM anomalies_history ORDER BY id DESC LIMIT 50", conn)
|
||||
if df.empty:
|
||||
print("Аномалии не найдены.")
|
||||
else:
|
||||
print(df.to_string(index=False))
|
||||
print("=" * 80 + "\n")
|
||||
|
||||
|
||||
def print_rules():
|
||||
"""Выводит правила базы знаний ИИ."""
|
||||
rules = get_all_rules_from_db()
|
||||
print("\n" + "=" * 80)
|
||||
print("🧠 ПРАВИЛА БАЗЫ ЗНАНИЙ ИИ:")
|
||||
print("=" * 80)
|
||||
if not rules:
|
||||
print("База знаний пуста.")
|
||||
else:
|
||||
for idx, r in enumerate(rules, 1):
|
||||
print(f" {idx}. {r}")
|
||||
print("=" * 80 + "\n")
|
||||
|
||||
|
||||
def dump_all_to_excel(out_filename="db_dump_full.xlsx"):
|
||||
"""Дампит всю базу SQLite во многостраничный Excel."""
|
||||
out_path = os.path.join(OUTPUT_DIR, out_filename)
|
||||
print(f"\n[🔄] Создание полного дампа БД в файл: {out_path} ...")
|
||||
with get_connection() as conn, pd.ExcelWriter(out_path, engine='openpyxl') as writer:
|
||||
for table in ['scud_logs', 'zup_staff', 'zup_absences', 'anomalies_history', 'ai_knowledge_base']:
|
||||
df = pd.read_sql_query(f"SELECT * FROM {table}", conn)
|
||||
df.to_excel(writer, sheet_name=table[:31], index=False)
|
||||
print(f"[✓] Дамп успешно сохранен: {out_path}\n")
|
||||
|
||||
|
||||
def print_system_prompts():
|
||||
"""Выводит все системные промпты из базы данных."""
|
||||
print("\n" + "=" * 80)
|
||||
print("📝 СИСТЕМНЫЕ ПРОМПТЫ (system_prompts):")
|
||||
print("=" * 80)
|
||||
with get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT id, name, is_active, updated_at, prompt_text FROM system_prompts ORDER BY id DESC")
|
||||
rows = cursor.fetchall()
|
||||
if not rows:
|
||||
print("Таблица system_prompts пуста.")
|
||||
else:
|
||||
for r in rows:
|
||||
print(f"ID: {r[0]} | Name: {r[1]} | Active: {r[2]} | Updated: {r[3]}")
|
||||
print("-" * 80)
|
||||
print(f"{r[4]}\n")
|
||||
print("=" * 80 + "\n")
|
||||
|
||||
|
||||
def print_session_states():
|
||||
"""Выводит текущие активные сессии и превью (session_states)."""
|
||||
print("\n" + "=" * 80)
|
||||
print("🔄 АКТИВНЫЕ СЕССИИ И ПРЕВЬЮ (session_states):")
|
||||
print("=" * 80)
|
||||
with get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT session_id, state_type, updated_at, pending_data FROM session_states")
|
||||
rows = cursor.fetchall()
|
||||
if not rows:
|
||||
print("Таблица session_states пуста (нет активных превью).")
|
||||
else:
|
||||
for r in rows:
|
||||
print(f"Session: {r[0]} | Type: {r[1]} | Updated: {r[2]}")
|
||||
print("-" * 80)
|
||||
print(f"Pending Data:\n{r[3]}\n")
|
||||
print("=" * 80 + "\n")
|
||||
|
||||
|
||||
HELP_TEXT = """
|
||||
CLI-утилита инспекции и управления SQLite базой данных СКУД (scud_orion_ai.db)
|
||||
|
||||
ДОСТУПНЫЕ КОМАНДЫ:
|
||||
stats -- Общая статистика строк по всем таблицам БД
|
||||
snapshots [ДД.ММ.ГГГГ] -- Посмотреть реестр снапшотов (опционально за конкретную дату)
|
||||
scud [ДД.ММ.ГГГГ] [--snapshot ID] [--export-xlsx NAME] -- Инспекция логов СКУД по дате/снапшоту и экспорт в Excel
|
||||
absences [ДД.ММ.ГГГГ] -- Посмотреть список официально отсутствующих из 1С:ЗУП
|
||||
anomalies -- Посмотреть историю найденных аномалий СКУД ⟷ 1С
|
||||
rules -- Посмотреть правила Базы Знаний ИИ из SQLite
|
||||
prompts -- Посмотреть системные промпты (system_prompts)
|
||||
sessions -- Посмотреть активные сессии и превью (session_states)
|
||||
dump [output.xlsx] -- Полный дамп всех таблиц БД в многостраничный Excel
|
||||
snapshot del [ID] или [--day ДД.ММ.ГГГГ] -- Удаление снапшота по ID или всех за выбранный день
|
||||
|
||||
ПРИМЕРЫ ЗАПУСКА:
|
||||
python scripts/db_cli.py stats
|
||||
python scripts/db_cli.py snapshots 06.08.2026
|
||||
python scripts/db_cli.py scud 06.08.2026 --export-xlsx срез_четверг
|
||||
python scripts/db_cli.py scud --snapshot Y20260805-007
|
||||
python scripts/db_cli.py absences 07.08.2026
|
||||
python scripts/db_cli.py prompts
|
||||
python scripts/db_cli.py sessions
|
||||
python scripts/db_cli.py snapshot del Y20260805-007
|
||||
python scripts/db_cli.py snapshot del --day 04.08.2026
|
||||
python scripts/db_cli.py dump my_dump.xlsx
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
if any(arg in sys.argv for arg in ['-h', '--help']):
|
||||
print(HELP_TEXT)
|
||||
sys.exit(0)
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
description=HELP_TEXT,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
add_help=False
|
||||
)
|
||||
parser.add_argument('command', nargs='?', default=None, choices=['stats', 'snapshots', 'scud', 'absences', 'anomalies', 'rules', 'prompts', 'sessions', 'dump', 'snapshot'], help="Основная команда")
|
||||
parser.add_argument('action', nargs='?', default=None, help="Дополнительное действие (например, 'del')")
|
||||
parser.add_argument('param', nargs='?', default=None, help="Параметр (дата, ID снапшота или имя файла)")
|
||||
parser.add_argument('--snapshot', type=str, default=None, help="ID конкретного снапшота для инспекции")
|
||||
parser.add_argument('--export-xlsx', type=str, default=None, help="Экспорт среза СКУД в Excel-файл")
|
||||
parser.add_argument('--day', type=str, default=None, help="Удалить снапшоты за конкретный день (ДД.ММ.ГГГГ)")
|
||||
|
||||
if len(sys.argv) == 1:
|
||||
print_stats()
|
||||
return
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.command == 'stats':
|
||||
print_stats()
|
||||
elif args.command == 'snapshots':
|
||||
date_val = args.param or args.action
|
||||
print_snapshots_list(date_str=date_val)
|
||||
elif args.command == 'scud':
|
||||
inspect_scud(snapshot_id=args.snapshot, date_str=args.param, export_xlsx=args.export_xlsx)
|
||||
elif args.command == 'absences':
|
||||
date_val = args.param or args.action
|
||||
print_absences(date_str=date_val)
|
||||
elif args.command == 'anomalies':
|
||||
print_anomalies()
|
||||
elif args.command == 'rules':
|
||||
print_rules()
|
||||
elif args.command == 'prompts':
|
||||
print_system_prompts()
|
||||
elif args.command == 'sessions':
|
||||
print_session_states()
|
||||
elif args.command == 'dump':
|
||||
filename = args.param if args.param else "db_dump_full.xlsx"
|
||||
dump_all_to_excel(filename)
|
||||
elif args.command == 'snapshot':
|
||||
if args.action == 'del':
|
||||
if args.day:
|
||||
delete_snapshots_by_date(args.day)
|
||||
elif args.param:
|
||||
delete_snapshot_by_id(args.param)
|
||||
else:
|
||||
print("\n[❌] Ошибка: Не указан ID снапшота или параметр --day для удаления.")
|
||||
print("Пример: python scripts/db_cli.py snapshot del Y20260805-007\n")
|
||||
else:
|
||||
print(f"\n[❌] Ошибка: Неизвестное действие '{args.action}' для команды snapshot.")
|
||||
print("Используйте: python scripts/db_cli.py snapshot del [ID или --day 'ДД.ММ.ГГГГ']\n")
|
||||
else:
|
||||
print(f"\n[❌] Ошибка: Неизвестная команда.")
|
||||
print(HELP_TEXT)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,47 @@
|
||||
import os
|
||||
import sqlite3
|
||||
|
||||
# Автопоиск файла базы данных в проекте
|
||||
db_path = 'data/scud_orion_ai.db' if os.path.exists('data/scud_orion_ai.db') else 'scud_orion_ai.db'
|
||||
|
||||
print("=" * 80)
|
||||
print(f"🔍 ДИАГНОСТИКА СУБД SQLITE: {db_path}")
|
||||
print("=" * 80)
|
||||
|
||||
if not os.path.exists(db_path):
|
||||
print(f"❌ Файл базы данных {db_path} не найден!")
|
||||
exit(1)
|
||||
|
||||
conn = sqlite3.connect(db_path)
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 1. Список всех таблиц и колонок
|
||||
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
|
||||
tables = [t[0] for t in cursor.fetchall()]
|
||||
|
||||
print("\n📋 СТРУКТУРА ТАБЛИЦ И КОЛИЧЕСТВО ЗАПИСЕЙ:")
|
||||
print("-" * 80)
|
||||
for t_name in tables:
|
||||
cursor.execute(f"PRAGMA table_info({t_name})")
|
||||
cols = [c[1] for c in cursor.fetchall()]
|
||||
|
||||
cursor.execute(f"SELECT COUNT(*) FROM {t_name}")
|
||||
count = cursor.fetchone()[0]
|
||||
|
||||
print(f"• [{t_name:<20}] — {count:>6} строк | Колонки: {cols}")
|
||||
|
||||
# 2. Просмотр правил Базы Знаний
|
||||
if 'ai_knowledge_base' in tables:
|
||||
print("\n" + "=" * 80)
|
||||
print("🧠 АКТУАЛЬНЫЕ ПРАВИЛА БАЗЫ ЗНАНИЙ (ai_knowledge_base):")
|
||||
print("=" * 80)
|
||||
cursor.execute("SELECT id, rule_text, added_by FROM ai_knowledge_base ORDER BY id ASC")
|
||||
rules = cursor.fetchall()
|
||||
if not rules:
|
||||
print("Таблица ai_knowledge_base пуста.")
|
||||
else:
|
||||
for r_id, r_text, r_author in rules:
|
||||
print(f" {r_id}. [{r_author}] {r_text}\n")
|
||||
|
||||
conn.close()
|
||||
print("=" * 80)
|
||||
@@ -0,0 +1,23 @@
|
||||
import os
|
||||
|
||||
print("=" * 80)
|
||||
print("📂 ТЕКУЩЕЕ СОСТОЯНИЕ ФАЙЛОВ ПРОЕКТА (scud_ai)")
|
||||
print("=" * 80)
|
||||
|
||||
total_files = 0
|
||||
total_size = 0
|
||||
|
||||
for root, dirs, files in os.walk('.'):
|
||||
# Исключаем служебные каталоги
|
||||
dirs[:] = [d for d in dirs if d not in ['.git', '__pycache__', 'venv', '.venv', 'extracted_project']]
|
||||
|
||||
for f in files:
|
||||
p = os.path.join(root, f)
|
||||
size = os.path.getsize(p)
|
||||
total_files += 1
|
||||
total_size += size
|
||||
print(f"{p:<55} ({size:>10,} bytes)".replace(',', ' '))
|
||||
|
||||
print("-" * 80)
|
||||
print(f"ИТОГО: файлов: {total_files} | Общий объем: {total_size / (1024 * 1024):.2f} MB")
|
||||
print("=" * 80)
|
||||
@@ -0,0 +1,31 @@
|
||||
import os
|
||||
|
||||
OUTPUT_SNAPSHOT = "project_code_snapshot.md"
|
||||
|
||||
# Расширения файлов для включения в снимок
|
||||
ALLOWED_EXTENSIONS = {'.py', '.json', '.md', '.sh', '.ini'}
|
||||
EXCLUDE_DIRS = {'.git', '__pycache__', 'venv', '.venv', 'output', 'logs', 'extracted_project'}
|
||||
EXCLUDE_FILES = {OUTPUT_SNAPSHOT, 'scud_orion_ai_v2.tar.gz', 'context_memory.db'}
|
||||
|
||||
print(f"🔄 Сборка полного контекстного слепка проекта в {OUTPUT_SNAPSHOT}...")
|
||||
|
||||
with open(OUTPUT_SNAPSHOT, 'w', encoding='utf-8') as out:
|
||||
out.write("# 📦 ПОЛНЫЙ ИСХОДНЫЙ КОД И КОНФИГУРАЦИЯ ПРОЕКТА scud_orion_ai_v2\n\n")
|
||||
|
||||
for root, dirs, files in os.walk('.'):
|
||||
dirs[:] = [d for d in dirs if d not in EXCLUDE_DIRS]
|
||||
|
||||
for file in sorted(files):
|
||||
ext = os.path.splitext(file)[1].lower()
|
||||
if ext in ALLOWED_EXTENSIONS and file not in EXCLUDE_FILES:
|
||||
filepath = os.path.join(root, file)
|
||||
out.write(f"## File: `{filepath}`\n")
|
||||
out.write("```" + (ext.replace('.', '') if ext != '.md' else '') + "\n")
|
||||
try:
|
||||
with open(filepath, 'r', encoding='utf-8', errors='replace') as f:
|
||||
out.write(f.read())
|
||||
except Exception as e:
|
||||
out.write(f"// Ошибка чтения файла: {e}\n")
|
||||
out.write("\n```\n\n")
|
||||
|
||||
print(f"✓ Успешно создан слепок проекта: {OUTPUT_SNAPSHOT} ({os.path.getsize(OUTPUT_SNAPSHOT):,} bytes)")
|
||||
@@ -0,0 +1,21 @@
|
||||
import os
|
||||
|
||||
EXCLUDE_DIRS = {'.git', '__pycache__', 'venv', '.venv', 'output', 'logs', 'extracted_project'}
|
||||
|
||||
def print_tree(startpath):
|
||||
print("=" * 60)
|
||||
print("📂 ДЕРЕВО АРХИТЕКТУРЫ ПРОЕКТА")
|
||||
print("=" * 60)
|
||||
for root, dirs, files in os.walk(startpath):
|
||||
dirs[:] = [d for d in dirs if d not in EXCLUDE_DIRS]
|
||||
level = root.replace(startpath, '').count(os.sep)
|
||||
indent = ' ' * 4 * (level)
|
||||
print(f'{indent}📁 {os.path.basename(root)}/')
|
||||
subindent = ' ' * 4 * (level + 1)
|
||||
for f in sorted(files):
|
||||
if not f.endswith('.pyc'):
|
||||
print(f'{subindent}📄 {f}')
|
||||
print("=" * 60)
|
||||
|
||||
if __name__ == "__main__":
|
||||
print_tree('.')
|
||||
@@ -0,0 +1,90 @@
|
||||
import sqlite3
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
DB_PATH = 'data/scud_orion_ai.db'
|
||||
|
||||
|
||||
def parse_to_date(date_str):
|
||||
"""Надежное преобразование даты логов и времени снапшота в объект date."""
|
||||
if not date_str:
|
||||
return None
|
||||
date_str = str(date_str).split(" ")[0].strip()
|
||||
if "." in date_str:
|
||||
try:
|
||||
return datetime.strptime(date_str, "%d.%m.%Y").date()
|
||||
except ValueError:
|
||||
return None
|
||||
elif "-" in date_str:
|
||||
try:
|
||||
return datetime.strptime(date_str, "%Y-%m-%d").date()
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def fix_snapshots():
|
||||
"""
|
||||
Переиндексирует снапшоты в таблице scud_logs.
|
||||
Нумерация веников (001, 002, 003...) сквозная внутри каждого ДНЯ СОЗДАНИЯ.
|
||||
Префикс Y выставляется только если дата логов < даты создания.
|
||||
"""
|
||||
if not os.path.exists(DB_PATH):
|
||||
print(f"База данных {DB_PATH} не найдена.")
|
||||
return
|
||||
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Группируем по уникальным выгрузкам
|
||||
cursor.execute("""
|
||||
SELECT snapshot_time, log_date
|
||||
FROM scud_logs
|
||||
WHERE snapshot_time IS NOT NULL
|
||||
GROUP BY snapshot_time, log_date
|
||||
ORDER BY snapshot_time ASC, log_date ASC
|
||||
""")
|
||||
rows = cursor.fetchall()
|
||||
|
||||
if not rows:
|
||||
print("Снапшоты не найдены.")
|
||||
conn.close()
|
||||
return
|
||||
|
||||
print("=== ИСПРАВЛЕНИЕ СКВОЗНОЙ НУМЕРАЦИИ ВНУТРИ ДНЯ СОЗДАНИЯ ===")
|
||||
|
||||
# Счетчик текущего порядкового номера strictly за ДЕНЬ СОЗДАНИЯ (YYYYMMDD)
|
||||
seq_counters = {}
|
||||
|
||||
for snap_time_raw, log_date_raw in rows:
|
||||
d_snap = parse_to_date(snap_time_raw)
|
||||
d_log = parse_to_date(log_date_raw)
|
||||
|
||||
if not d_snap or not d_log:
|
||||
continue
|
||||
|
||||
date_prefix = d_snap.strftime("%Y%m%d")
|
||||
|
||||
# Если дата логов строго раньше даты создания снапшота — ставим Y
|
||||
is_yesterday = (d_log < d_snap)
|
||||
prefix = "Y" if is_yesterday else ""
|
||||
|
||||
# Приращиваем сквозной счетчик за ЭТОТ ДЕНЬ СОЗДАНИЯ
|
||||
seq_counters[date_prefix] = seq_counters.get(date_prefix, 0) + 1
|
||||
seq_num = seq_counters[date_prefix]
|
||||
|
||||
new_id = f"{prefix}{date_prefix}-{seq_num:03d}"
|
||||
|
||||
cursor.execute(
|
||||
"UPDATE scud_logs SET snapshot_id = ? WHERE snapshot_time = ? AND log_date = ?",
|
||||
(new_id, snap_time_raw, log_date_raw)
|
||||
)
|
||||
print(f" • Срез создания: {snap_time_raw} | Логи за: {log_date_raw} ===> Назначен ID: [{new_id}]")
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
print("\n[✓] Переиндексация внутри дней создания успешно выполнена!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
fix_snapshots()
|
||||
Reference in New Issue
Block a user