Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
f05dcf1
Add venv to .gitignore
Anarchy73 Feb 27, 2026
6c83a1f
Add __pycache__ to .gitignore
Anarchy73 Feb 27, 2026
5082c09
Add Fastapi example
Anarchy73 Feb 27, 2026
0f4f8b9
Feat(app): add fastapi test router with parser
Anarchy73 Feb 27, 2026
a3c7349
chore: add .venv to .gitignore
Anarchy73 Mar 22, 2026
91ed560
feat (app): add ParseResponse schema
Anarchy73 Mar 22, 2026
3192dbb
feat(app): add upload endpoint
Anarchy73 Mar 22, 2026
f77921d
fix(app): fix uuid response and async file read
Anarchy73 Mar 22, 2026
81cea1f
chore: add uploads dir to .gitignore
Anarchy73 Mar 22, 2026
fd5d4a4
feat(app): add docker compose with solr
Anarchy73 Mar 23, 2026
68706a5
Merge branch 'fastapi/artsolo' into fastapi/nomenconservandum
NomenConservandum May 23, 2026
6d2feb0
Implement basic working cycle
NomenConservandum May 23, 2026
e857deb
0.3. Finished I suppose
NomenConservandum May 28, 2026
4257d72
0.4. Finished
NomenConservandum May 28, 2026
52fbd1c
Finish 1.2
NomenConservandum May 29, 2026
b0894c3
Finish 1
NomenConservandum Jun 6, 2026
a255c12
Finish 1#2
NomenConservandum Jun 12, 2026
4c81807
Update front-end; Add: Docs CRUD
NomenConservandum Jun 12, 2026
4d0d568
refactor front-end
NomenConservandum Jun 12, 2026
94e165d
Finish phase 3?; Update front-end
NomenConservandum Jun 12, 2026
303e27a
Add AI assistent?
NomenConservandum Jun 12, 2026
56a42c5
Add: alembic support
NomenConservandum Jun 13, 2026
2ea49d1
Implement: Groups
NomenConservandum Jun 13, 2026
762b5bf
Remove temporary patch and test scripts
NomenConservandum Jun 14, 2026
293e3a9
Fix: sources availability in AI-chat
NomenConservandum Jun 14, 2026
fd2748f
Fix: post-register redirection; Add: document metadata at modal window
NomenConservandum Jun 14, 2026
96d6d1c
Fix: not-in-any-group users cannot create restricted-access documents
NomenConservandum Jun 14, 2026
503c014
Add: document-search by name, pagination
NomenConservandum Jun 14, 2026
5ccefe2
Add: group access editing
NomenConservandum Jun 14, 2026
f0d3da3
Remove alien front-end elements
NomenConservandum Jun 14, 2026
1f0423b
refactor front-end
NomenConservandum Jun 14, 2026
b04f3ff
Add: theme switcher
NomenConservandum Jun 14, 2026
b30db69
Remove: strange symbols
NomenConservandum Jun 17, 2026
3ac248e
Minor details
NomenConservandum Jun 17, 2026
663bb3a
chore(parser): cargo clippy fixes
aragami3070 Aug 21, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.venv
venv
__pycache__
*.pyc
.git
.env
storage
alembic/versions/*.pyc
2 changes: 2 additions & 0 deletions .env.local
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/docs_db
SOLR_URL=http://localhost:8983/solr/chunks
18 changes: 12 additions & 6 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
# Created by venv; see https://docs.python.org/3/library/venv.html
bin/
include/
lib/
*lib64*
target/
*.so
_rels/
docProps/
media/
word/
*.xml
share/
.env*
pyvenv.cfg
tree.txt
*__pycache__*
uploads/*
report/
25 changes: 25 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
FROM python:3.11-slim

WORKDIR /app

# Установка системных зависимостей
RUN apt-get update && apt-get install -y gcc libpq-dev && rm -rf /var/lib/apt/lists/*

# Копирование requirements и установка
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Копирование всего приложения
COPY ./app /app
COPY ./scripts /scripts

# Создание директории для кэша моделей
RUN mkdir -p /app/model_cache

# Установка PYTHONPATH
ENV PYTHONPATH=/app

EXPOSE 8000

# Запуск: ждём БД, создаём таблицы, запускаем uvicorn
CMD ["sh", "-c", "python /scripts/wait_for_db.py && python /scripts/init_db.py && uvicorn app.main:app --host 0.0.0.0 --port 8000"]
156 changes: 135 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,34 +1,148 @@
# Docs search
<!-- здесь должно быть описание проекта -->
# Корпоративная RAG-система для работы с приватными документами

## Зависимости и их установка
### Ubuntu
Docs Search - это корпоративная система для семантического поиска и ИИ-анализа документов. Проект использует FastAPI для бэкенда, Qdrant для векторного поиска, PostgreSQL для метаданных и пользователей, а также локальную языковую модель (`cointegrated/rubert-tiny2`) для создания эмбеддингов.

## Системные требования

- **ОС:** Linux (Ubuntu/Debian, Arch Linux и др.)
- **Среда:** Python 3.10+
- **Инфраструктура:** Docker и Docker Compose (для запуска баз данных PostgreSQL и Qdrant)

---

## Установка и первый запуск

Данная инструкция описывает развёртывание проекта для локальной разработки и тестирования, где базы данных работают в Docker-контейнерах, а сам FastAPI-сервер запускается напрямую в виртуальном окружении.

### 1. Установка системных зависимостей

Вам потребуются инструменты для компиляции и библиотеки OCR (Tesseract):

**Ubuntu/Debian:**
```bash
sudo apt update
sudo apt install -y build-essential pkg-config clang llvm-dev libclang-dev \
libleptonica-dev libtesseract-dev tesseract-ocr \
tesseract-ocr-rus tesseract-ocr-eng python3 python3-pip
tesseract-ocr-rus tesseract-ocr-eng python3 python3-pip python3-venv
```

### Arch Linux
**Arch Linux:**
```bash
sudo pacman -Syu --needed --noconfirm build-essential pkgconf clang llvm \
leptonica tesseract tesseract-data-rus \
tesseract-data-eng python-pip
```

- maturin:
```bash
# Запускаете .venv
pip install maturin
```
## Как запускать? (работа только в .venv окружении)
- Билдим rust либу
```bash
cd parser
maturin develop
```
- Запускаем python
```bash
python main.py
```
### 2. Настройка виртуального окружения (Python)

Перейдите в директорию проекта, создайте и активируйте виртуальное окружение:

```bash
python3 -m venv .venv
source .venv/bin/activate
```

Установите все необходимые зависимости:
```bash
pip install -r requirements.txt
```

### 3. Конфигурация переменных окружения (`.env`)

Для работы приложению требуются ключи и настройки баз данных. Создайте в корне проекта файл `.env` со следующим содержимым:

```ini
# Доступы к PostgreSQL
POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres
POSTGRES_DB=docs_db
DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/docs_db

# Секретные ключи для JWT
JWT_SECRET_KEY=your_super_secret_key_here
JWT_REFRESH_SECRET_KEY=your_super_refresh_secret_here
JWT_ALGORITHM=HS256
JWT_ACCESS_EXPIRE_MINUTES=60
JWT_REFRESH_EXPIRE_DAYS=7

# Учетные данные суперадминистратора
ADMIN_USERNAME=...
ADMIN_PASSWORD=...

# API Ключи для ИИ чата (если используются GigaChat/DeepSeek)
GIGACHAT_API_KEY=...
DEEPSEEK_API_KEY=...

# Интеграция локальной LLM через Ollama (опционально)
OLLAMA_HOST=http://localhost:11434
OLLAMA_MODEL=llama3
```

*(Обязательно замените секретные ключи на надёжные значения в рабочей среде).*

### 4. Запуск баз данных (Docker)

Запустите PostgreSQL и Qdrant в фоне с помощью Docker Compose:

```bash
docker compose up -d
```
Эта команда создаст контейнеры `docs_postgres` (порт 5432) и `docs_qdrant` (порт 6333) и сохранит их данные в Docker Volumes, чтобы они не исчезли после перезапуска.

### 5. Применение миграций схемы БД

Чтобы создать необходимые таблицы в базе данных PostgreSQL, выполните миграции Alembic.
*(Убедитесь, что виртуальное окружение `.venv` активировано!)*

```bash
export $(grep -v '^#' .env | xargs)
alembic upgrade head
```

### 6. Запуск Backend сервера

Теперь всё готово для запуска основного приложения:

```bash
# Экспортируем переменные окружения и запускаем FastAPI
export $(grep -v '^#' .env | xargs)
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
```

---

## Использование системы

- **Веб-интерфейс:** Откройте в браузере [http://localhost:8000/ui/](http://localhost:8000/ui/).
- **Вход в систему:** Используйте логин `admin` и пароль `admin1234` (указанные в `.env`), чтобы получить права администратора.
- **API Документация (Swagger):** Доступна по адресу [http://localhost:8000/docs](http://localhost:8000/docs).

*Примечание: При первом запуске сервер скачает NLP-модель (`cointegrated/rubert-tiny2`), что может занять от нескольких секунд до пары минут в зависимости от скорости интернет-соединения.*

---

## Разработка: Работа с миграциями (Alembic)

Alembic используется для управления схемой базы данных. Это позволяет легко синхронизировать изменения таблиц.

**Создать новую миграцию** после изменения схемы в файле `app/models.py`:
```bash
alembic revision --autogenerate -m "описание_изменений"
```

**Применить все ожидающие миграции:**
```bash
alembic upgrade head
```

**Откатить последнюю миграцию:**
```bash
alembic downgrade -1
```

**Проверить текущее состояние:**
```bash
alembic current # Текущая версия
alembic check # Есть ли незафиксированные изменения
alembic history # История миграций
```
149 changes: 149 additions & 0 deletions alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts.
# this is typically a path given in POSIX (e.g. forward slashes)
# format, relative to the token %(here)s which refers to the location of this
# ini file
script_location = %(here)s/alembic

# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s

# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory. for multiple paths, the path separator
# is defined by "path_separator" below.
prepend_sys_path = .

# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the tzdata library which can be installed by adding
# `alembic[tz]` to the pip requirements.
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =

# max length of characters to apply to the "slug" field
# truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version location specification; This defaults
# to <script_location>/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "path_separator"
# below.
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions

# path_separator; This indicates what character is used to split lists of file
# paths, including version_locations and prepend_sys_path within configparser
# files such as alembic.ini.
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
# to provide os-dependent path splitting.
#
# Note that in order to support legacy alembic.ini files, this default does NOT
# take place if path_separator is not present in alembic.ini. If this
# option is omitted entirely, fallback logic is as follows:
#
# 1. Parsing of the version_locations option falls back to using the legacy
# "version_path_separator" key, which if absent then falls back to the legacy
# behavior of splitting on spaces and/or commas.
# 2. Parsing of the prepend_sys_path option falls back to the legacy
# behavior of splitting on spaces, commas, or colons.
#
# Valid values for path_separator are:
#
# path_separator = :
# path_separator = ;
# path_separator = space
# path_separator = newline
#
# Use os.pathsep. Default configuration used for new projects.
path_separator = os


# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

# database URL. This is consumed by the user-maintained env.py script only.
# other means of configuring database URLs may be customized within the env.py
# file.
sqlalchemy.url =


[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples

# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME

# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
# hooks = ruff
# ruff.type = module
# ruff.module = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME

# Alternatively, use the exec runner to execute a binary found on your PATH
# hooks = ruff
# ruff.type = exec
# ruff.executable = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME

# Logging configuration. This is also consumed by the user-maintained
# env.py script only.
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARNING
handlers = console
qualname =

[logger_sqlalchemy]
level = WARNING
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
1 change: 1 addition & 0 deletions alembic/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration with an async dbapi.
Loading
Loading