• About Us
  • Disclaimer
  • Contact Us
  • Privacy Policy
Thursday, July 23, 2026
mGrowTech
No Result
View All Result
  • Technology And Software
    • Account Based Marketing
    • Channel Marketing
    • Marketing Automation
      • Al, Analytics and Automation
      • Ad Management
  • Digital Marketing
    • Social Media Management
    • Google Marketing
  • Direct Marketing
    • Brand Management
    • Marketing Attribution and Consulting
  • Mobile Marketing
  • Event Management
  • PR Solutions
  • Technology And Software
    • Account Based Marketing
    • Channel Marketing
    • Marketing Automation
      • Al, Analytics and Automation
      • Ad Management
  • Digital Marketing
    • Social Media Management
    • Google Marketing
  • Direct Marketing
    • Brand Management
    • Marketing Attribution and Consulting
  • Mobile Marketing
  • Event Management
  • PR Solutions
No Result
View All Result
mGrowTech
No Result
View All Result
Home Al, Analytics and Automation

A Coding Implementation to Build an AI-Powered File Type Detection and Security Analysis Pipeline with Magika and OpenAI

Josh by Josh
April 19, 2026
in Al, Analytics and Automation
0
A Coding Implementation to Build an AI-Powered File Type Detection and Security Analysis Pipeline with Magika and OpenAI


!pip install magika openai -q


import os, io, json, zipfile, textwrap, hashlib, tempfile, getpass
from pathlib import Path
from collections import Counter
from magika import Magika
from magika.types import MagikaResult, PredictionMode
from openai import OpenAI


print("🔑 Enter your OpenAI API key (input is hidden):")
api_key = getpass.getpass("OpenAI API Key: ")
client  = OpenAI(api_key=api_key)


try:
   client.models.list()
   print("✅ OpenAI connected successfully\n")
except Exception as e:
   raise SystemExit(f"❌ OpenAI connection failed: {e}")


m = Magika()
print("✅ Magika loaded successfully\n")
print(f"   module version : {m.get_module_version()}")
print(f"   model name     : {m.get_model_name()}")
print(f"   output types   : {len(m.get_output_content_types())} supported labels\n")


def ask_gpt(system: str, user: str, model: str = "gpt-4o", max_tokens: int = 600) -> str:
   resp = client.chat.completions.create(
       model=model,
       max_tokens=max_tokens,
       messages=[
           {"role": "system", "content": system},
           {"role": "user",   "content": user},
       ],
   )
   return resp.choices[0].message.content.strip()


print("=" * 60)
print("SECTION 1 — Core API + GPT Plain-Language Explanation")
print("=" * 60)


samples = {
   "Python":     b'import os\ndef greet(name):\n    print(f"Hello, {name}")\n',
   "JavaScript": b'const fetch = require("node-fetch");\nasync function getData() { return await fetch("/api"); }',
   "CSV":        b'name,age,city\nAlice,30,NYC\nBob,25,LA\n',
   "JSON":       b'{"name": "Alice", "scores": [10, 20, 30], "active": true}',
   "Shell":      b'#!/bin/bash\necho "Hello"\nfor i in $(seq 1 5); do echo $i; done',
   "PDF magic":  b'%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\n',
   "ZIP magic":  bytes([0x50, 0x4B, 0x03, 0x04]) + bytes(26),
}


print(f"\n{'Label':<12} {'MIME Type':<30} {'Score':>6}")
print("-" * 52)
magika_labels = []
for name, raw in samples.items():
   res = m.identify_bytes(raw)
   magika_labels.append(res.output.label)
   print(f"{res.output.label:<12} {res.output.mime_type:<30} {res.score:>5.1%}")


explanation = ask_gpt(
   system="You are a concise ML engineer. Explain in 4–5 sentences.",
   user=(
       f"Magika is Google's AI file-type detector. It just identified these types from raw bytes: "
       f"{magika_labels}. Explain how a deep-learning model detects file types from "
       "just bytes, and why this beats relying on file extensions."
   ),
   max_tokens=250,
)
print(f"\n💬 GPT on how Magika works:\n{textwrap.fill(explanation, 72)}\n")


print("=" * 60)
print("SECTION 2 — Batch Identification + GPT Summary")
print("=" * 60)


tmp_dir = Path(tempfile.mkdtemp())
file_specs = {
   "code.py":     b"import sys\nprint(sys.version)\n",
   "style.css":   b"body { font-family: Arial; margin: 0; }\n",
   "data.json":   b'[{"id": 1, "val": "foo"}, {"id": 2, "val": "bar"}]',
   "script.sh":   b"#!/bin/sh\necho Hello World\n",
   "doc.html":    b"<html><body><p>Hello</p></body></html>",
   "config.yaml": b"server:\n  host: localhost\n  port: 8080\n",
   "query.sql":   b"CREATE TABLE t (id INT PRIMARY KEY, name TEXT);\n",
   "notes.md":    b"# Heading\n\n- item one\n- item two\n",
}


paths = []
for fname, content in file_specs.items():
   p = tmp_dir / fname
   p.write_bytes(content)
   paths.append(p)


results       = m.identify_paths(paths)
batch_summary = [
   {"file": p.name, "label": r.output.label,
    "group": r.output.group, "score": f"{r.score:.1%}"}
   for p, r in zip(paths, results)
]


print(f"\n{'File':<18} {'Label':<14} {'Group':<12} {'Score':>6}")
print("-" * 54)
for row in batch_summary:
   print(f"{row['file']:<18} {row['label']:<14} {row['group']:<12} {row['score']:>6}")


gpt_summary = ask_gpt(
   system="You are a DevSecOps expert. Be concise and practical.",
   user=(
       f"A file upload scanner detected these file types in a batch: "
       f"{json.dumps(batch_summary)}. "
       "In 3–4 sentences, summarise what kind of project this looks like "
       "and flag any file types that might warrant extra scrutiny."
   ),
   max_tokens=220,
)
print(f"\n💬 GPT project analysis:\n{textwrap.fill(gpt_summary, 72)}\n")



Source_link

READ ALSO

Professor Emeritus Dimitri Bertsekas, influential computer scientist and prolific author, dies at 83 | MIT News

Unsloth vs Axolotl vs TRL vs LLaMA-Factory: A Fine-Tuning Framework Comparison on Speed, VRAM, and Multi-GPU

Related Posts

Professor Emeritus Dimitri Bertsekas, influential computer scientist and prolific author, dies at 83 | MIT News
Al, Analytics and Automation

Professor Emeritus Dimitri Bertsekas, influential computer scientist and prolific author, dies at 83 | MIT News

July 22, 2026
Unsloth vs Axolotl vs TRL vs LLaMA-Factory: A Fine-Tuning Framework Comparison on Speed, VRAM, and Multi-GPU
Al, Analytics and Automation

Unsloth vs Axolotl vs TRL vs LLaMA-Factory: A Fine-Tuning Framework Comparison on Speed, VRAM, and Multi-GPU

July 22, 2026
FDA-Ready Medical Image Annotation Guide for Healthcare AI
Al, Analytics and Automation

FDA-Ready Medical Image Annotation Guide for Healthcare AI

July 22, 2026
Poolside Releases Laguna S 2.1, an Open-Weight Agentic Coding Model Punching Above Its Weight Class on SWE-Bench Multilingual
Al, Analytics and Automation

Poolside Releases Laguna S 2.1, an Open-Weight Agentic Coding Model Punching Above Its Weight Class on SWE-Bench Multilingual

July 22, 2026
Meta Open-Sources Astryx: An Agent-Ready React Design System With 150+ Accessible Components, Seven Themes, and a CLI
Al, Analytics and Automation

Meta Open-Sources Astryx: An Agent-Ready React Design System With 150+ Accessible Components, Seven Themes, and a CLI

July 21, 2026
Alibaba’s Tongyi Lab Releases Qwen-Audio-3.0-TTS, a Hosted Text-to-Speech Model in Flash and Plus Tiers Across 16 Languages
Al, Analytics and Automation

Alibaba’s Tongyi Lab Releases Qwen-Audio-3.0-TTS, a Hosted Text-to-Speech Model in Flash and Plus Tiers Across 16 Languages

July 21, 2026
Next Post
Anthropic just launched Claude Design, an AI tool that turns prompts into prototypes and challenges Figma

Anthropic just launched Claude Design, an AI tool that turns prompts into prototypes and challenges Figma

POPULAR NEWS

Trump ends trade talks with Canada over a digital services tax

Trump ends trade talks with Canada over a digital services tax

June 28, 2025
15 Trending Songs on TikTok in 2025 (+ How to Use Them)

15 Trending Songs on TikTok in 2025 (+ How to Use Them)

June 18, 2025
Communication Effectiveness Skills For Business Leaders

Communication Effectiveness Skills For Business Leaders

June 10, 2025
App Development Cost in Singapore: Pricing Breakdown & Insights

App Development Cost in Singapore: Pricing Breakdown & Insights

June 22, 2025
Comparing the Top 7 Large Language Models LLMs/Systems for Coding in 2025

Comparing the Top 7 Large Language Models LLMs/Systems for Coding in 2025

November 4, 2025

EDITOR'S PICK

Google’s AI bounty program pays bug hunters up to $30K

Google’s AI bounty program pays bug hunters up to $30K

October 9, 2025
How AI Target Audience Tools Help Identify Your Core Buyers

How AI Target Audience Tools Help Identify Your Core Buyers

July 15, 2025
How To Build Consumer Trust In Health Tech Through PR

How To Build Consumer Trust In Health Tech Through PR

July 11, 2025

Inside the playbook of a PR pro guiding startups through hypergrowth

June 7, 2025

About

We bring you the best Premium WordPress Themes that perfect for news, magazine, personal blog, etc. Check our landing page for details.

Follow us

Categories

  • Account Based Marketing
  • Ad Management
  • Al, Analytics and Automation
  • Brand Management
  • Channel Marketing
  • Digital Marketing
  • Direct Marketing
  • Event Management
  • Google Marketing
  • Marketing Attribution and Consulting
  • Marketing Automation
  • Mobile Marketing
  • PR Solutions
  • Social Media Management
  • Technology And Software
  • Uncategorized

Recent Posts

  • The credential that let OpenAI's agents into Hugging Face exists in most enterprises right now
  • How Brands Can Escape AI-Driven Sameness
  • How to use your Gemini Live camera for real-time help
  • MoEngage adquire Aampe para construir a CEP AgĂȘntica, alimentada por Tomada de DecisĂ”es AgĂȘnticas 1:1
  • About Us
  • Disclaimer
  • Contact Us
  • Privacy Policy
No Result
View All Result
  • Technology And Software
    • Account Based Marketing
    • Channel Marketing
    • Marketing Automation
      • Al, Analytics and Automation
      • Ad Management
  • Digital Marketing
    • Social Media Management
    • Google Marketing
  • Direct Marketing
    • Brand Management
    • Marketing Attribution and Consulting
  • Mobile Marketing
  • Event Management
  • PR Solutions