Skip to main content

Multipurpose python utils

Project description

JANIA LIB

Librería multipropósito en Python: utilidades para procesamiento de configuración, extracción de datos de PDF usando LLM y limpieza avanzada de JSON.

Instalación

Requiere Python 3.7 o superior.

pip install jania

O bien, clona el repositorio:

git clone https://github.com/julianin/JANIALIB.git
cd JANIALIB
pip install .

Dependencias

  • toml
  • PyYAML
  • python-dotenv
  • pymupdf
  • Pillow
  • openai

Funcionalidades principales

1. Limpieza y formateo de JSON: cleanJSON

Función para extraer, limpiar y formatear el primer bloque JSON válido de un texto (útil para outputs de LLM o APIs poco estrictas).

Uso básico:

from jania import cleanJSON
json_str = cleanJSON(raw_text)

Parámetros:

  • text: (str) Texto de entrada donde buscar JSON.
  • indent: (int, opcional) Espacios de indentación para el JSON de salida. Default: 2.
  • debug: (bool, opcional) Si es True, también devuelve el fragmento corregido que se intentó parsear. Default: False.

Devuelve:

  • Un string con el JSON limpio y formateado, o None si no se encuentra JSON válido.

Ejemplo:

json_str = cleanJSON('output: {a:1, b:2, c:true}')
print(json_str)
# {
#   "a": 1,
#   "b": 2,
#   "c": true
# }

2. Gestión de configuración: env y env_config

Utilidades para leer configuración multi-formato y variables de entorno, con prioridad flexible.

env_config(filename)

Carga un archivo de configuración extra (acepta .py, .toml, .yaml/.yml, .json, .txt). El archivo se usará como fuente prioritaria tras el entorno.

Uso:

from jania import env, env_config
env_config('settings.toml')

Parámetro:

  • filename: Ruta al archivo de configuración.

env(key, fallback=None)

Busca el valor de una clave de configuración (str) siguiendo este orden:

  1. Variable de entorno
  2. Config cargado por env_config()
  3. config.py
  4. settings.toml
  5. settings.yaml
  6. fallback (valor por defecto)

Uso:

valor = env('API_KEY', fallback='1234')

Devuelve:

  • Valor de la clave (str) o fallback si no se encuentra.

3. Extracción y análisis de PDF con LLM: extractPDF

Convierte cada página de un PDF a imagen y consulta un modelo LLM Vision (por defecto: gpt-4-vision-preview) para analizarlo.

Uso típico:

from jania import extractPDF
with open('documento.pdf', 'rb') as f:
    respuesta = extractPDF(
        prompt='Resume el documento:',
        archivo=f,
        nombre_archivo='documento.pdf',
        model='gpt-4-vision-preview',  # opcional
        max_images=10,                 # opcional
        openai_api_key=None            # opcional
    )

Parámetros:

  • prompt: (str) Instrucción para el LLM.
  • archivo: (BinaryIO) Archivo PDF abierto en modo binario.
  • nombre_archivo: (str) Nombre del archivo (para almacenamiento temporal).
  • model: (str, opcional) Modelo de OpenAI Vision a usar. Default: "gpt-4-vision-preview".
  • max_images: (int, opcional) Número máximo de páginas/imágenes a procesar. Default: 10.
  • openai_api_key: (str, opcional) API Key de OpenAI. Si no se da, se busca en configuración/env.

Devuelve:

  • Diccionario con la respuesta del LLM bajo la clave respuesta_llm.

Notas:

  • Requiere la librería openai y una API Key válida.
  • Si no tienes la clave, colócala en una variable de entorno OPENAI_API_KEY o config compatible.

Ejemplo de uso general

from jania import env, env_config
from jania import cleanJSON
from jania import extractPDF

# Configuración
env_config('settings.toml')
clave = env('OPENAI_API_KEY')

# Limpieza de JSON
json_str = cleanJSON('Responde en json: {"x":1, "y":true, "z":null}')

# Análisis de PDF
with open('ejemplo.pdf', 'rb') as f:
    resultado = extractPDF('Describe cada página', f, 'ejemplo.pdf', openai_api_key=clave)
    print(resultado['respuesta_llm'])

Licencia

MIT

Autor

Julian Ania

NOTES

git tag -a v0.3.1 -m "Release v0.3.1"
git push origin  v0.3.1

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

jania-0.3.10.tar.gz (6.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

jania-0.3.10-py3-none-any.whl (6.7 kB view details)

Uploaded Python 3

File details

Details for the file jania-0.3.10.tar.gz.

File metadata

  • Download URL: jania-0.3.10.tar.gz
  • Upload date:
  • Size: 6.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for jania-0.3.10.tar.gz
Algorithm Hash digest
SHA256 f23d11becaf696624a255c9e72a80dee53aaf1e51eaba00c6787b03e534bccc4
MD5 d801e256272ba8c75a02fafbf9a9792e
BLAKE2b-256 1b5b6b23be138dde1737e5f2760169e232434dec34d332c97718cb6f7d6c8182

See more details on using hashes here.

Provenance

The following attestation bundles were made for jania-0.3.10.tar.gz:

Publisher: publish.yml on julianin/JANIALIB

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file jania-0.3.10-py3-none-any.whl.

File metadata

  • Download URL: jania-0.3.10-py3-none-any.whl
  • Upload date:
  • Size: 6.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for jania-0.3.10-py3-none-any.whl
Algorithm Hash digest
SHA256 c66cbfeb46bbbdf26785543bb371316389e07ce3e6e9e325f71fd8aa96e3965a
MD5 2248d323da6bd3482462eb9f077de564
BLAKE2b-256 30183b8d90aae0b42f3a68ae3313d73119b5d1432f9fc2abfa0d0f5668d85438

See more details on using hashes here.

Provenance

The following attestation bundles were made for jania-0.3.10-py3-none-any.whl:

Publisher: publish.yml on julianin/JANIALIB

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page