
Быстрое и точное обнаружение типов содержимого файлов на основе ИИ
Magika — это инновационный инструмент для определения типов файлов на основе ИИ, который использует последние достижения глубокого обучения для обеспечения точного обнаружения. Внутри Magika использует собственную, высокооптимизированную модель, которая весит всего несколько мегабайт, и обеспечивает точную идентификацию файлов за миллисекунды, даже при работе на одном процессоре. Magika был обучен и оценен на наборе данных из ~100 миллионов образцов, охватывающем более 200 типов контента (включая как бинарные, так и текстовые форматы), и достигает средней точности ~99% на нашем тестовом наборе.
Вот как выглядит пример вывода командной строки Magika:
Magika используется в масштабе для повышения безопасности пользователей Google, направляя файлы Gmail, Drive и Safe Browsing в соответствующие сканеры безопасности и политики контента, обрабатывая сотни миллиардов образцов еженедельно. Magika также интегрирован с VirusTotal (пример) и abuse.ch (пример).
Для получения дополнительной информации вы можете прочитать наш первоначальный анонс в блоге Google OSS, посетить веб-сайт Magika и узнать больше в нашей исследовательской статье, опубликованной на IEEE/ACM International Conference on Software Engineering (ICSE) 2025.
Вы можете попробовать Magika без установки, воспользовавшись нашим веб-демо, которое работает локально в вашем браузере!
-r для рекурсивного сканирования каталога.high-confidence, medium-confidence и best-guess.Magika поставляется с CLI на Rust, который можно установить несколькими способами.
Via magika python package:
pipx install magika
Через brew (macOS / Linux)
brew install magika
Через установочный скрипт:
curl -LsSf https://securityresearch.google/magika/install.sh | sh
или:
powershell -ExecutionPolicy Bypass -c "irm https://securityresearch.google/magika/install.ps1 | iex"
Через пакет Rust magika-cli:
cargo install --locked magika-cli
pip install magika
npm install magika
Здесь вы найдёте несколько быстрых примеров, чтобы начать работу.
Чтобы узнать о внутреннем устройстве Magika, посмотрите раздел Core Concepts на веб-сайте Magika.
% cd tests_data/basic && magika -r * | head
asm/code.asm: Assembly (code)
batch/simple.bat: DOS batch file (code)
c/code.c: C source (code)
css/code.css: CSS source (code)
csv/magika_test.csv: CSV document (code)
dockerfile/Dockerfile: Dockerfile (code)
docx/doc.docx: Microsoft Word 2007+ document (document)
docx/magika_test.docx: Microsoft Word 2007+ document (document)
eml/sample.eml: RFC 822 mail (text)
empty/empty_file: Empty file (inode)
% magika ./tests_data/basic/python/code.py --json
[
{
"path": "./tests_data/basic/python/code.py",
"result": {
"status": "ok",
"value": {
"dl": {
"description": "Python source",
"extensions": [
"py",
"pyi"
],
"group": "code",
"is_text": true,
"label": "python",
"mime_type": "text/x-python"
},
"output": {
"description": "Python source",
"extensions": [
"py",
"pyi"
],
"group": "code",
"is_text": true,
"label": "python",
"mime_type": "text/x-python"
},
"score": 0.996999979019165
}
}
}
]
% cat tests_data/basic/ini/doc.ini | magika -
-: INI configuration file (text)
% magika --help
Determines file content types using AI
Usage: magika [OPTIONS] [PATH]...
Arguments:
[PATH]...
List of paths to the files to analyze.
Use a dash (-) to read from standard input (can only be used once).
Options:
-r, --recursive
Identifies files within directories instead of identifying the directory itself
--no-dereference
Identifies symbolic links as is instead of identifying their content by following them
--colors
Prints with colors regardless of terminal support
--no-colors
Prints without colors regardless of terminal support
-s, --output-score
Prints the prediction score in addition to the content type
-i, --mime-type
Prints the MIME type instead of the content type description
-l, --label
Prints a simple label instead of the content type description
--json
Prints in JSON format
--jsonl
Prints in JSONL format
--format <CUSTOM>
Prints using a custom format (use --help for details).
The following placeholders are supported:
%p The file path
%l The unique label identifying the content type
%d The description of the content type
%g The group of the content type
%m The MIME type of the content type
%e Possible file extensions for the content type
%s The score of the content type for the file
%S The score of the content type for the file in percent
%b The model output if overruled (empty otherwise)
%% A literal %
-h, --help
Print help (see a summary with '-h')
-V, --version
Print version
Дополнительные примеры и документацию по CLI можно найти на https://crates.io/crates/magika-cli.
>>> from magika import Magika
>>> m = Magika()
>>> res = m.identify_bytes(b'function log(msg) {console.log(msg);}')
>>> print(res.output.label)
javascript
>>> from magika import Magika
>>> m = Magika()
>>> res = m.identify_path('./tests_data/basic/ini/doc.ini')
>>> print(res.output.label)
ini
>>> from magika import Magika
>>> m = Magika()
>>> with open('./tests_data/basic/ini/doc.ini', 'rb') as f:
>>> res = m.identify_stream(f)
>>> print(res.output.label)
ini
Дополнительные примеры и документацию по Python модулю можно найти в разделе Python Magika module.
Пожалуйста, обратитесь к веб-сайту Magika для получения подробной документации о:
Пожалуйста, свяжитесь с нами напрямую по адресу [email protected].
Apache 2.0; подробности см. в LICENSE.
Этот проект не является официальным проектом Google. Он не поддерживается Google, и Google отказывается от всех гарантий в отношении его качества, товарной пригодности или пригодности для конкретной цели.