Add a filter (or setting?) to allow alt text generation when the site has basic authentication

Abierto
#895 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
32/100
Tipo de issue
Nueva funcionalidad
Claridad
Bastante claro
Estado de actividad
Estancado
Stack tecnológico
php
Área
ai, backend

Línea de trabajo

Comienza en el filtro classifai_openai_api_request_post_options y sigue la ruta de la solicitud de texto alternativo para classifai_feature_descriptive_text_generator. Compara las opciones de solicitud existentes con la solución alternativa de basic-auth proporcionada; el trabajo debería considerarse terminado cuando se puedan procesar imágenes de sitios protegidos con basic-auth sin requerir que el proveedor las obtenga directamente.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Is your enhancement related to a problem? Please describe.

Right now alt text generation fails when basic authentication is enabled because OpenAI (or whichever provider) can't access the image directly.

This code works specifically for my use-case, but I'm wondering if there is a way to more easily handle this while we're working on protected staging sites.

/**
 * Handle basic auth for Classifai alt text generation via OpenAI.
 *
 * @param array  $options The options.
 * @param string $url     The URL.
 * @param string $feature The feature.
 *
 * @return array
 */
add_filter( 'classifai_openai_api_request_post_options', function( array $options, string $url, string $feature ): array {
	// Bail if not our feature.
	if ( 'classifai_feature_descriptive_text_generator' !== $feature ) {
		return $options;
	}

	// Bail if no body.
	if ( ! isset( $options['body'] ) ) {
		return $options;
	}

	// Bail if no messages.
	$body = json_decode( $options['body'], true );
	if ( ! $body || empty( $body['messages'] ) ) {
		return $options;
	}

	// Set the username and password.
	$un = 'someun';
	$pw = 'somepw';

	// Encode the credentials.
	$creds = base64_encode( $un . ':' . $pw );

	// Loop through the messages.
	foreach ( $body['messages'] as &$message ) {
		// Bail if not an array.
		if ( ! is_array( $message['content'] ) ) {
			continue;
		}

		// Loop through the items.
		foreach ( $message['content'] as &$item ) {
			// Bail if not an image.
			if ( empty( $item['type'] ) || 'image_url' !== $item['type'] ) {
				continue;
			}

			// Fetch the image manually.
			$resp = wp_remote_get( $item['image_url']['url'], [
				'headers' => [ 'Authorization' => 'Basic ' . $creds ],
			] );

			// Bail if error.
			if ( is_wp_error( $resp ) ) {
				continue;
			}

			// Get the raw body.
			$raw  = wp_remote_retrieve_body( $resp );

			// Encode the body.
			$b64  = base64_encode( $raw );

			// Figure out the MIME type (fallback to jpeg).
			$info = @getimagesizefromstring( $raw );
			$mime = $info ? $info['mime'] : 'image/jpeg';

			// Replace with a Data URI.
			$item = [
				'type'      => 'image_url',
				'image_url' => [
					'url'    => "data:{$mime};base64,{$b64}",
					'detail' => $item['image_url']['detail'] ?? 'auto',
				],
			];
		}
	}

	// Encode the body.
	$options['body'] = wp_json_encode( $body );

	return $options;

}, 10, 3  );
Designs

No response

Describe alternatives you've considered

No response

Code of Conduct
  • I agree to follow this project's Code of Conduct
Lenguaje dominante
PHP
Estrellas
714
Forks
68
Merge medio
4 h 32 min
PR fusionados (30 d)
23

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de 10up/classifai

Todos los issues de 10up/classifai

Issues similares

Más issues de PHP

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.