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.7.tar.gz (5.9 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.7-py3-none-any.whl (6.6 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: jania-0.3.7.tar.gz
  • Upload date:
  • Size: 5.9 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.7.tar.gz
Algorithm Hash digest
SHA256 a3cafbe42f50f8f66c07f23a60b2587936e4b74ac0b18123afce8daf48dad25a
MD5 1369ad7b5ecc86a5bb76efd1bd6aec71
BLAKE2b-256 a9695574b3fe36e0cf755527a1bce079b43381a6dc07792f1ec999a6a7eb2996

See more details on using hashes here.

Provenance

The following attestation bundles were made for jania-0.3.7.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.7-py3-none-any.whl.

File metadata

  • Download URL: jania-0.3.7-py3-none-any.whl
  • Upload date:
  • Size: 6.6 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.7-py3-none-any.whl
Algorithm Hash digest
SHA256 0c9fafdddc179c66b4bbb99c68d2e784454ce4116362636d912a8a73333e085e
MD5 a690ef924501bc28e2ac1ca8e2fd5cef
BLAKE2b-256 f8d3f036b418d25dcabe8cecb479bc7569d6ddc27e2ccf84126971a24de630ba

See more details on using hashes here.

Provenance

The following attestation bundles were made for jania-0.3.7-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