just-not-google/BiNeuron: BiNeuron is a local AI assistant that detects programming languages from requests/files, selects spe

github.com · 2026-10-04 · by Long Nguyen ·github
BiNeuron is a local AI assistant that detects programming languages from requests/files, selects specialized models based on hardware, and generates code/docs/analysis via configurable prompts. It extracts text from PDFs, Word, images (OCR), and other formats, translates, filters profanity, and uses proxies if needed. Runs offline. - just-not-google/BiNeuron

just-not-google/BiNeuron

BiNeuron is a local AI assistant that detects programming languages from requests/files, selects specialized models based on hardware, and generates code/docs/analysis via configurable prompts. It ...

10 stars · 2 forks

README

BiNeuron

🇬🇧 English Intelligent Code Analysis and Generation Platform BiNeuron is a sophisticated software solution that bridges the gap between human intent and machine generated code. It unifies advanced natural language processing, optical character recognition, and adaptive model selection into a single, powerful tool designed for developers, researchers, and technical teams. At its core, BiNeuron automatically identifies the programming language of a given request, extracts content from a wide array of file formats, including images and documents, and then generates context aware, production ready code using best in class local or cloud based language models. Key Capabilities Programming Language Detection

Supports over 25 programming languages, including Python, Java, C/C++, C#, JavaScript, TypeScript, Go, Rust, Swift, Kotlin, Ruby, Dart, Julia, Lua, SQL, MATLAB, R, Pascal, Assembly, Fortran, F#, Ada, Zig, PHP, Shell, Scala, PowerShell, Solidity, OCaml, COBOL, and more. Combines heuristic algorithms, proprietary keyword matching, and AI powered orchestration to achieve high detection accuracy. Analyzes both user supplied text and the content of attached files, or even entire directories.

Comprehensive File Handling

Extracts and translates text from common document formats: PDF, Word (DOCX), ODF, PowerPoint (PPTX), Excel (XLSX/XLS), EPUB, MOBI, and FB2. Processes source code files in nearly all text based formats, from plain text to configuration files. Integrates two interchangeable OCR engines (EasyOCR and DeepSeek OCR) to read text from images, with optional GPU acceleration, language list selection, and automatic splitting of large images (crop_mode) for improved recognition. Reads text from websites: the built in HTML scraper (use_websites) converts pages to clean Markdown and merges them into the request context.

AI Powered File Editing

Two Stage Pipeline: The primary AI model generates the code or response. A secondary, lightweight model (e.g., Qwen2.5-Coder-1.5B) then transforms the response into a strict JSON object containing absolute file paths and full new contents. Full Context Awareness: The JSON formatter receives the complete file context (all read files, unread file names, project root, and the primary AI’s answer) to ensure accurate path generation and content mapping. Robust Retry Mechanism: If the JSON fails validation, the system automatically re prompts the formatter up to retries times, logging each attempt until a valid JSON is produced or the maximum retries are exhausted. Safe, Whole File Replacements: Only whole file replacements are supported (no partial edits) to maintain consistency and safety. Optional File Deletion: When deleting_files=True is passed to the BiNeuron constructor, the JSON formatter may return null for a file path, and the system will safely delete that file. This feature is disabled by default to prevent accidental data loss.

Adaptive Model Selection

Automatically assesses the user’s hardware capabilities (CPU cores, frequency, RAM) and selects the optimal quantized version of the target model (ranging from IQ2 to F16) to balance speed and accuracy. Offers a curated repository of specialised models per programming language, ensuring high quality, idiomatic code generation.

Robust Networking

Implements multi layered accessibility to Hugging Face models, including automatic fallback to hf mirror.com, dynamic proxy selection, and support for custom proxy lists. Fetches and verifies public proxies from GitHub raw lists, with retry mechanisms and connection health checks.

Virtual Storage Mode

Allows scanning and processing of entire folders or mounted virtual directories. Recursively identifies supported files, extracts their content, and incorporates it into the analysis context, which is perfect for large codebases or repositories. Interactive File Explorer: In GUI mode, the virtual storage is displayed as a tree view. Double click any file to open it in the default system application.

Multilingual Translation

Built in translation engine normalises user requests to English (or any configured target language) to ensure consistent AI interactions. Supports both Google Translate and DeepL, with automatic fallback when network restrictions are detected. Offline Translation: Optional ArgosTranslate integration (local_trans=True, from_code_lang='en') provides fully offline translation without relying on external APIs.

Text Enhancement and Compression

Request Improvement (improving_user_experience=True): A local small model (Qwen) rewrites the user’s raw request into a clear, structured prompt while preserving all technical details, including file names, code fragments, and error messages. Lossless Text Compression (compress_text=True): When a large amount of file context is attached, the same small model compresses it, aggressively reducing token count while preserving every fact, number, and code fragment verbatim.

Privacy and Security

Request Anonymization (anonymize_text=True): Before being sent to translation services or AI models, the user’s request is processed through Microsoft Presidio, which detects and replaces PII (names, emails, phone numbers, addresses, credit cards, etc.) with placeholder tokens. Profanity Filter (filter_for_swearing=True): Blocks requests containing aggressive language or profanity before they reach the AI. Chat Encryption: Optionally protect all stored conversations with a master password using Fernet (AES 128 CBC + HMAC SHA256) with PBKDF2 HMAC SHA256 key derivation (200,000 iterations). After three failed unlock attempts the entire chat database and master key are permanently wiped.

Architecture BiNeuron is engineered with a modular, separation of concerns design:

Core Engine orchestrates the entire pipeline: request parsing, language detection, model selection, and response generation. OCR Module handles text extraction from images via two interchangeable engines: EasyOCR and DeepSeek OCR (local HF Transformers or cloud API). Model Downloader manages downloading and caching of Hugging Face models, with built in mirror and proxy support. JSON Formatter Module uses a lightweight model (e.g., Qwen2.5-Coder-1.5B) to convert the primary model’s response into a strict JSON object for file modifications. File Editing Module applies JSON based file changes (whole file replacements) with error handling and retry logic. Supports optional file deletion when deleting_files=True. Text Enhancement Module handles request improvement (PROMPT_FOR_IMPROVEMENT) and lossless compression (PROMPT_FOR_COMPRESSION) via the same lightweight model. Translation Service provides language detection and translation utilities, with optional DeepL and ArgosTranslate integration. Anonymization Service integrates Microsoft Presidio for PII detection and masking. Network Layer implements proxy rotation, availability checks, and GitHub proxy fetching for circumventing restrictions. Web Interface is a feature rich web application built with Flask (HTML/CSS/JS), covering every configurable parameter of the nine configuration groups.

The architecture emphasises reusability, fault tolerance, and performance, allowing each component to operate independently while seamlessly integrating with the others. Graphical Interface

A modern web application built with Flask, offering:

Intuitive Chat Interface: message history, file attachments, and real time log display. Virtual Storage Explorer: scan and navigate directories in a tree view. Comprehensive Settings Panel: fine tune every aspect of the platform, including network, model selection, prompt mode, translator, OCR, file handling, safety, and more. Chat Management: create, delete, download, and filter conversation history. Live Logging: see what the AI is doing in real time (with spinner, deduplicated progress bars, and one click copy). Master Password Encryption: enable or disable chat encryption directly from the UI. 24 Dark Themes: from Midnight Deep and Dracula’s Castle to Synthwave ’84, Matrix Terminal, and AMOLED Black; every theme is tuned for long coding sessions. Session Resume: if the page is reloaded while a request is running, the client reconnects to the ongoing task automatically. Multilingual UI: English, Russian, and Chinese.

Development Only the interface and the interaction with the interface were developed with the help of DeepSeek Coder. This includes the Flask based web UI, the JavaScript front end, and the user interaction logic. All other components, including the core engine, OCR module, model downloader, JSON formatter, file editing module, translation service, anonymization service, network layer, and overall architecture, were designed and written independently.

Model Collection: deepseek-ai/deepseek-coder Example Model: deepseek-ai/deepseek-coder-6.7b-instruct

Configuration Groups The platform exposes nine independent configuration groups, all available from the web UI:

Group Purpose

ModelConfig Model selection, cache directory, HF token, repo/filename overrides, mirror preference

LLMConfig Context size, GPU layers, max tokens, temperature, verbose/echo flags

PromptConfig Main prompt mode (11 pre set scenarios), custom prompt, request improvement

TranslationConfig Determinant mode, DeepL, request language, offline Argos translation

LanguageDetectionConfig AI orchestrator vs. proprietary keyword matching

ProxyConfig Country, protocol, timeouts, retries, custom/GitHub proxy lists

OCRConfig Engine selection (Easy/DeepSeek), languages, GPU, crop mode, cloud API key

FileConfig Virtual storage, file editing, file deletion, website scraping, compression, ignored files

SafetyConfig Profanity filter, request anonymization

Dependencies The complete list of libraries used by BiNeuron (exactly as declared in requirements.txt). Core & AI

Library Purpose Repository

torch Tensor computation and GPU acceleration for local models github.com/pytorch/pytorch

transformers Loading and running Hugging Face models locally github.com/huggingface/transformers

huggingface_hub Downloading and caching models from Hugging Face github.com/huggingface/huggingface_hub

llama-cpp-python Running GGUF models via llama.cpp bindings github.com/abetlen/llama-cpp-python

pillow Image loading and preprocessing for OCR and vision models github.com/python-pillow/Pillow

OCR

Library Purpose Repository

easyocr OCR engine for text extraction from images github.com/JaidedAI/EasyOCR

deepseek-ocr DeepSeek OCR client (local and cloud) pypi.org/project/deepseek-ocr

Document Parsing

Library Purpose Repository

PyMuPDF Reading text from PDF files github.com/pymupdf/PyMuPDF

docx2txt Extracting text from .docx (Microsoft Word) github.com/ankushshah89/python-docx2txt

pptx2txt2 Extracting text from .pptx (PowerPoint) pypi.org/project/pptx2txt2

odfdo Reading OpenDocument (.odf) files github.com/jdum/odfdo

markitdown Universal document converter (used for .xlsx/.xls) github.com/microsoft/markitdown

epub2txt Extracting text from EPUB e-books pypi.org/project/epub2txt

mobi Extracting text from MOBI e-books github.com/iscc/mobi

fb2reader Reading FictionBook 2 (.fb2) files pypi.org/project/fb2reader

html2text Converting HTML pages to clean Markdown github.com/Alir3z4/html2text

Translation

Library Purpose Repository

deep-translator Free translation via Google Translate (and others) github.com/nidhaloff/deep-translator

deepl Official DeepL API client github.com/DeepLcom/deepl-python

argostranslate Fully offline translation via Argos Translate github.com/argosopentech/argos-translate

langdetect Language detection (fallback algorithm) github.com/Mimino666/langdetect

fast-langdetect Fast language detection (primary algorithm) github.com/LlmKira/fast-langdetect

Language & Code Detection

Library Purpose Repository

codelang-detect Detecting programming language by code sample pypi.org/project/codelang-detect

whats_that_code Independent programming language detection github.com/matthewdeanmartin/whats_that_code

badwords-py Profanity filtering (imports as badwords) pypi.org/project/badwords-py

Privacy & Anonymization

Library Purpose Repository

presidio-analyzer PII detection engine (Microsoft Presidio) github.com/microsoft/presidio

presidio-anonymizer Anonymization engine for detected PII github.com/microsoft/presidio

Networking & Proxies

Library Purpose Repository

requests HTTP client for REST calls and proxy checks github.com/psf/requests

httpx Async capable HTTP client used with proxies github.com/encode/httpx

free-proxy-server Fetching and filtering free proxy lists pypi.org/project/free-proxy-server

Web & System

Library Purpose Repository

flask Web server and REST API for the GUI github.com/pallets/flask

psutil Reading system info (CPU, RAM) for benchmarking github.com/giampaolo/psutil

cryptography Encrypting chats with a master password (Fernet) github.com/pyca/cryptography

CLI, Testing & Packaging

Library Purpose Repository

pytest Test runner github.com/pytest-dev/pytest

pyinstaller Building standalone executables github.com/pyinstaller/pyinstaller

Model Repository BiNeuron leverages a hand picked collection of open source code generation models, each fine tuned for specific programming languages. The repository includes models from DeepSeek, Qwen, MiniMax, CodeLlama, Mellum, Wizard, and others. The system automatically fetches the appropriate model based on the detected language and the user’s hardware profile, ensuring optimal performance for every session.

BiNeuron represents a fusion of cutting edge AI, robust software engineering, and practical usability, empowering developers to focus on creativity and problem solving while the platform handles the complexities of language detection, file processing, and model orchestration.

🇷🇺 Русский Интеллектуальная платформа для анализа и генерации кода BiNeuron представляет собой сложное программное решение, которое устраняет разрыв между намерениями человека и машинным кодом. Он объединяет продвинутую обработку естественного языка, оптическое распознавание символов и адаптивный выбор модели в единый мощный инструмент, предназначенный для разработчиков, исследователей и технических групп. По своей сути, BiNeuron автоматически определяет язык программирования для данного запроса, извлекает содержимое из широкого спектра форматов файлов, включая изображения и документы, а затем генерирует контекстно зависимый, готовый к работе код, используя лучшие в своем классе локальные или облачные языковые модели. Ключевые возможности Определение языка программирования

Поддерживает более 25 языков программирования, включая Python, Java, C/C++, C#, JavaScript, TypeScript, Go, Rust, Swift, Kotlin, Ruby, Dart, Julia, Lua, SQL, MATLAB, R, Pascal, Assembly, Fortran, F#, Ada, Zig, PHP, Shell, Scala, PowerShell, Solidity, OCaml, COBOL и другие. Объединяет эвристические алгоритмы, фирменный поиск по ключевым словам и ИИ управляемую оркестрацию для высокой точности определения. Анализирует как текст, введённый пользователем, так и содержимое прикреплённых файлов или даже целых каталогов.

Всесторонняя обработка файлов

Извлекает и преобразует текст из распространённых форматов документов: PDF, Word (DOCX), ODF, PowerPoint (PPTX), Excel (XLSX/XLS), EPUB, MOBI и FB2. Обрабатывает файлы исходного кода почти во всех текстовых форматах, от обычного текста до конфигурационных файлов. Интегрирует два взаимозаменяемых OCR движка (EasyOCR и DeepSeek OCR) для чтения текста из изображений, с опциональным ускорением на GPU, выбором списка языков и автоматическим разбиением больших изображений (crop_mode) для улучшенного распознавания. Читает текст с сайтов: встроенный HTML скрапер (use_websites) конвертирует страницы в чистый Markdown и добавляет их в контекст запроса.

Изменение файлов с помощью ИИ

Двухэтапный пайплайн: Основная ИИ модель генерирует код или ответ. Вторичная лёгкая модель (например, Qwen2.5-Coder-1.5B) преобразует этот ответ в строгий JSON объект, содержащий абсолютные пути к файлам и новое полное содержимое. Полный контекст: Форматтер JSON получает весь контекст файлов (все прочитанные файлы, имена непрочитанных файлов, корень проекта и ответ основной ИИ модели) для точной генерации путей и содержимого. Надёжный механизм повторных попыток: Если JSON не проходит валидацию, система автоматически перезапрашивает форматтер до retries раз, логируя каждую попытку, пока не будет получен валидный JSON или не будут исчерпаны все попытки. Безопасная замена целых файлов: Поддерживается только полная замена файлов (не частичное редактирование) для обеспечения согласованности и безопасности. Опциональное удаление файлов: При передаче deleting_files=True в конструктор BiNeuron JSON форматтер может вернуть null для пути к файлу, и система безопасно удалит этот файл. По умолчанию функция отключена во избежание случайной потери данных.

Адаптивный выбор модели

Автоматически оценивает аппаратные возможности пользователя (количество ядер CPU, частота, ОЗУ) и выбирает оптимальную квантизованную версию целевой модели (от IQ2 до F16) для баланса скорости и точности. Предлагает специально подобранный репозиторий моделей для каждого языка программирования, обеспечивая высококачественную и идиоматичную генерацию кода.

Надёжные сетевые возможности

Реализует многоуровневый доступ к моделям Hugging Face, включая автоматическое переключение на hf mirror.com, динамический выбор прокси и поддержку пользовательских списков прокси. Загружает и проверяет публичные прокси из списков GitHub, с повторными попытками и проверкой работоспособности соединений.

Режим виртуального хранилища

Позволяет сканировать и обрабатывать целые папки или смонтированные виртуальные директории. Рекурсивно определяет поддерживаемые файлы, извлекает их содержимое и включает его в контекст анализа, что идеально для больших кодовых баз или репозиториев. Интерактивный файловый менеджер: В режиме GUI виртуальное хранилище отображается в виде дерева. Двойной клик по файлу открывает его в системном приложении по умолчанию.

Многоязычный перевод

Встроенный механизм перевода приводит запросы пользователя к английскому (или любому другому настроенному языку) для единообразного взаимодействия с ИИ. Поддерживает Google Translate и DeepL с автоматическим переключением при обнаружении сетевых ограничений. Офлайн перевод: Опциональная интеграция ArgosTranslate (local_trans=True, from_code_lang='en') обеспечивает полностью офлайн перевод без обращения к внешним API.

Улучшение и сжатие текста

Улучшение запроса (improving_user_experience=True): Локальная малая модель (Qwen) переписывает исходный запрос пользователя в чёткий структурированный промпт, сохраняя все технические детали, включая имена файлов, фрагменты кода, сообщения об ошибках. Без потерь сжатие текста (compress_text=True): Когда к запросу прикреплено много файлов, та же малая модель агрессивно сокращает их объём, сохраняя каждый факт, число и фрагмент кода дословно.

Приватность и безопасность

Анонимизация запроса (anonymize_text=True): Перед отправкой в сервисы перевода или ИИ модели запрос пользователя проходит через Microsoft Presidio, который находит и заменяет PII (имена, email, телефоны, адреса, банковские карты и т. д.) на токены заглушки. Фильтр ненормативной лексики (filter_for_swearing=True): Блокирует запросы, содержащие агрессию или мат, до их попадания в ИИ. Шифрование чатов: Возможность защитить все сохранённые беседы мастер паролем с использованием Fernet (AES 128 CBC + HMAC SHA256) и PBKDF2 HMAC SHA256 (200 000 итераций). После трёх неудачных попыток разблокировки база чатов и мастер ключ безвозвратно удаляются.

Архитектура BiNeuron спроектирован по модульному принципу с разделением ответственности:

Основной движок управляет всем конвейером: разбор запроса, определение языка, выбор модели и генерация ответа. Модуль

source

github.com · 9 images · 158 links

Comments (0)

No comments yet