Usa Llama 3 y Moondream para navegar, auditar seguridad y analizar imágenes.

¿Alguna vez deseaste que tu terminal fuera inteligente? Hoy vamos a crear “Q”, un asistente híbrido que vive en tu consola. Gracias a Ollama, este script puede entender órdenes en lenguaje natural y utilizar visión artificial para buscar archivos visualmente.

🛡️ Seguridad y Auditoría Automática

Con este script, puedes realizar auditorías de seguridad rápidas. Pregunta cosas como:

  • “¿Hay conexiones remotas activas?”
  • “Revisa si alguien ha intentado hackear mi PC”
  • “¿Qué usuarios han iniciado sesión recientemente?”

📦 Requisitos Previos

Primero, instala Ollama y las librerías necesarias:

# Instalar modelos
ollama pull llama3
ollama pull moondream

# Instalar librería de procesamiento de imagen
pip install Pillow

🐍 El Script Completo: ia-term-viva.py

Guarda el siguiente código en tu carpeta personal como ia-term-viva.py:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import subprocess, sys, time, re, os, base64

# Colores para la terminal
BLUE = '\033[94m'; GREEN = '\033[92m'; YELLOW = '\033[93m'
CYAN = '\033[96m'; MAGENTA = '\033[95m'; RED = '\033[91m'
RESET = '\033[0m'; BOLD = '\033[1m'

def typing_print(text, speed=0.02):
    for char in text:
        sys.stdout.write(char); sys.stdout.flush(); time.sleep(speed)
    print()

def image_to_base64(image_path):
    try:
        with open(image_path, "rb") as img_file:
            return base64.b64encode(img_file.read()).decode('utf-8')
    except: return None

def vision_analyze(prompt, image_path):
    img_b64 = image_to_base64(image_path)
    if not img_b64: return "ERROR"
    result = subprocess.run(
        ["ollama", "run", "moondream"],
        input=f"{prompt}\nimage: {img_b64}",
        text=True, capture_output=True, encoding="utf-8"
    )
    return result.stdout.strip()

def run_llama_logic(prompt_input):
    model = "llama3"
    system_instructions = (
        "Eres un experto en terminal Linux y Seguridad Informatica. "
        "Traduce la peticion a un comando Bash puro. FORMATO: Frase | comando."
    )
    res = subprocess.run(
        ["ollama", "run", model], 
        input=f"{system_instructions}\n\nUsuario: {prompt_input}", 
        text=True, capture_output=True, encoding="utf-8"
    )
    return res.stdout.strip()

def main():
    if len(sys.argv) < 2:
        print(f"{CYAN}¿Qué órdenes tienes, Julio César?{RESET}"); return

    query = " ".join(sys.argv[1:])

    # --- LÓGICA DE VISIÓN (MOONDREAM) ---
    if "busca" in query.lower() and ("persona" in query.lower() or "playera" in query.lower() or "imagen" in query.lower()):
        print(f"{YELLOW}👁️  Activando Moondream...{RESET}")
        carpeta = os.getcwd()
        if "en " in query.lower():
            pos_ruta = query.lower().split("en ")[-1].strip()
            if os.path.isdir(pos_ruta): carpeta = pos_ruta
            elif pos_ruta in ["esta carpeta", ".", "aquí"]: carpeta = os.getcwd()

        objetivo = query.lower().split("busca")[-1].split("en")[0].strip()
        fotos = [f for f in os.listdir(carpeta) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))]

        for foto in fotos:
            ruta = os.path.join(carpeta, foto)
            print(f"🧐 Analizando: {foto}...", end="\r")
            res = vision_analyze(f"Is there {objetivo} in this image? Answer only yes or no.", ruta)
            if "yes" in res.lower():
                print(f"\n{GREEN}✅ ENCONTRADA: {foto}{RESET}")
                subprocess.run(["xdg-open", ruta]); return 
        print(f"\n{RED}Sin resultados.{RESET}"); return

    # --- LÓGICA DE TERMINAL (LLAMA 3) ---
    raw_output = run_llama_logic(query)
    if "|" in raw_output:
        partes = raw_output.split("|")
        frase, comando = partes[0].strip(), "|".join(partes[1:]).strip()
    else:
        frase, comando = "Entendido", raw_output.strip()

    comando = comando.replace("`", "").replace("bash", "").strip().split('\n')[0]
    print(f"\n{BOLD}{BLUE}🤖 Terminal:{RESET} ", end="")
    typing_print(f"'{frase}'")

    if len(comando) > 1:
        print(f"{MAGENTA}💻 Ejecutando:{RESET} {GREEN}{BOLD}{comando}{RESET}")
        with open("/tmp/last_ia_cmd", "w") as f: f.write(comando)
        subprocess.run(comando, shell=True)

if __name__ == "__main__":
    main()

⚙️ Configuración del Alias (.bashrc)

Para habilitar el comando q y permitir la navegación cd, añade esto al final de tu archivo ~/.bashrc:

q() {
    python3 ~/ia-term-viva.py "$@"
    if [ -f /tmp/last_ia_cmd ]; then
        local cmd=$(cat /tmp/last_ia_cmd)
        if [[ "$cmd" == cd* ]]; then eval "$cmd"; fi
        rm -f /tmp/last_ia_cmd
    fi
}

#Linux #InteligenciaArtificial #Ollama #Ciberseguridad #Python