# jasurkhon/self-service-bot architecture

> Architecture diagram of the GitHub repository jasurkhon/self-service-bot, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-09-24). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/jasurkhon/self-service-bot
- Repository: https://github.com/jasurkhon/self-service-bot

## Overview

##### Project Type and Purpose
- This is a specialized Telegram chatbot (“bot.py”), enhanced with two‐factor authentication and an embedded machine‐learning retrieval algorithm.
- Its primary use case: authenticated users send free‐form queries via Telegram, the bot locates semantically similar entries in a preprocessed knowledge base (CSV + vector file), and returns the best match.

##### File‐Structure Analysis
Top‐level files and their roles:
- bot.py – Core chatbot logic: receives Telegram updates, enforces 2FA, invokes ML retrieval, sends replies.
- app.py – Orchestration script (e.g., launch routines, config loader, or local testing harness).
- NewVec.npy – NumPy array of precomputed embeddings for the KB.
- preprocessed_kb_base.csv – Tabular knowledge base with matched text & metadata.
- np.txt – Temporary storage for closest matches (logging or quick-lookup).
- consumer.sqlite – SQLite database for runtime user‐session data (2FA tokens, conversation state).
- customer.sql – SQL dump of registered users & credentials.
- requirements.txt – Lists frameworks: pyTelegramBotAPI, numpy, pandas, torch, transformers, scikit-learn, seaborn.

##### Key Components
a. Telegram Client (External Service)
– Users interact via Telegram’s API.
b. Bot Logic Layer (bot.py)
– Subcomponents:
- 2FA Module (generates/verifies codes, stores tokens in consumer.sqlite)
- Query Processor (prepares user text, calls embedding+search)
- Response Formatter (packages selected KB entry back to user)
c. ML Retrieval Engine
– Preprocessing & vector model (uses torch + transformers)
– Vector Store (NewVec.npy) + Metadata Store (preprocessed_kb_base.csv)
– Similarity Search (e.g., sklearn or custom cosine computation)
d. Persistence Layer
– consumer.sqlite: session/2FA state
– customer.sql → relational DB of user credentials (pre‐loaded)
e. Auxiliary Files
– np.txt: ephemeral cache/log of recent similarity results
f. Orchestration Script (app.py)
– Configuration loader for paths, credentials, external model dir (deeppavlov-rubert)
– Launches bot.py or performs initial data checks

##### Component Interactions & Data Flows
1. User → Telegram API → bot.py (Webhook or Polling)
2. bot.py → 2FA Module → consumer.sqlite (read/write OTP state)
3. On authenticated query: bot.py → Query Processor → loads embedding model → loads NewVec.npy + preprocessed_kb_base.csv → computes similarity → writes top results to np.txt (optional)
4. ML Engine → returns best match → bot.py formats message → Telegram API → User
5. On startup: app.py reads requirements, ensures model folder (deeppavlov-rubertbasecased) is in place, then spawns bot.py

##### Architectural Patterns & Design Principles
- Separation of Concerns: Authentication logic, ML retrieval, and messaging handled in discrete modules.
- Data locality: Precompute embeddings (NewVec.npy) to avoid recomputing at runtime.
- Single‐process, file‐based persistence (SQLite) for lightweight state management.
- External dependency isolation: requirements.txt pins all libraries.

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% External systems
    User["User"]:::external
    TelegramAPI["Telegram API"]:::external

    %% Application modules
    subgraph "Application Layer"
        Orchestration["Orchestration Script\n(app.py)"]:::app
        BotLogic["Bot Logic\n(bot.py)"]:::app
        subgraph "Bot Submodules"
            twoFAModule["2FA Module"]:::app
            QueryProcessor["Query Processor"]:::app
            ResponseFormatter["Response Formatter"]:::app
        end
    end

    %% ML Retrieval Engine
    subgraph "ML Retrieval Engine"
        EmbeddingModel["Embedding Model\n(torch/transformers)"]:::ml
        SimilaritySearch["Similarity Search\n(sklearn/cosine)"]:::ml
    end

    %% Data Stores
    subgraph "Data Stores"
        consumerDB["SQLite DB\n(consumer.sqlite)"]:::datastore
        credentialsDB["User Credentials\n(customer.sql)"]:::datastore
    end

    %% ML Artifacts
    subgraph "ML Artifacts"
        VectorStore["Vector Store\n(NewVec.npy)"]:::datastore
        MetadataStore["Metadata Store\n(preprocessed_kb_base.csv)"]:::datastore
    end

    %% Auxiliary files
    npCache["np.txt\n(Temp Cache)"]:::aux
    requirements["requirements.txt"]:::aux
    readme["README.md"]:::aux

    %% Connections
    User -->|"sends query"| TelegramAPI
    TelegramAPI -->|"webhook/polling"| BotLogic
    BotLogic -->|"invoke"| twoFAModule
    twoFAModule -->|"read/write OTP"| consumerDB
    BotLogic -->|"on auth"| QueryProcessor
    QueryProcessor -->|"load model"| EmbeddingModel
    QueryProcessor -->|"load data"| VectorStore
    QueryProcessor -->|"load data"| MetadataStore
    QueryProcessor -->|"compute similarity"| SimilaritySearch
    SimilaritySearch -->|"top results"| npCache
    SimilaritySearch -->|"best match"| BotLogic
    BotLogic -->|"format response"| ResponseFormatter
    ResponseFormatter -->|"send reply"| TelegramAPI
    TelegramAPI -->|"delivers reply"| User

    %% Startup flow
    Orchestration -->|"reads config"| requirements
    Orchestration -->|"initial checks"| EmbeddingModel
    Orchestration -->|"launch"| BotLogic

    %% Documentation link
    Orchestration --> readme

    %% Click events
    click BotLogic "https://github.com/jasurkhon/self-service-bot/blob/main/bot.py"
    click Orchestration "https://github.com/jasurkhon/self-service-bot/blob/main/app.py"
    click VectorStore "https://github.com/jasurkhon/self-service-bot/blob/main/NewVec.npy"
    click MetadataStore "https://github.com/jasurkhon/self-service-bot/blob/main/preprocessed_kb_base.csv"
    click consumerDB "https://github.com/jasurkhon/self-service-bot/blob/main/consumer.sqlite"
    click credentialsDB "https://github.com/jasurkhon/self-service-bot/blob/main/customer.sql"
    click npCache "https://github.com/jasurkhon/self-service-bot/blob/main/np.txt"
    click requirements "https://github.com/jasurkhon/self-service-bot/blob/main/requirements.txt"
    click readme "https://github.com/jasurkhon/self-service-bot/blob/main/README.md"

    %% Styles
    classDef external fill:#ADD8E6,stroke:#000,stroke-width:1px
    classDef app fill:#98FB98,stroke:#000,stroke-width:1px
    classDef ml fill:#FFD700,stroke:#000,stroke-width:1px
    classDef datastore fill:#FFA500,stroke:#000,stroke-width:1px
    classDef aux fill:#F0E68C,stroke:#000,stroke-width:1px
```
