Cookie Consent by Free Privacy Policy Generator Update cookies preferences 📌 Angular + Gemini Pro Vision

🏠 Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeiträge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden Überblick über die wichtigsten Aspekte der IT-Sicherheit in einer sich ständig verändernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch übersetzen, erst Englisch auswählen dann wieder Deutsch!

Google Android Playstore Download Button für Team IT Security



📚 Angular + Gemini Pro Vision


💡 Newskategorie: Programmierung
🔗 Quelle: dev.to

Esta es la segunda parte de una serie de artículos sobre Angular + Gemini

Integrando Angular y Gemini Pro Vision

Bienvenido a la segunda parte de este tutorial en el que daremos una introducción a cómo integrar Angular y Gemini Vision Pro de una forma muy sencilla.

Empezando:

1. Actualizar nuestro gemini.service para que reciba archivos

Para poder enviar imágenes a nuestro modelo de Gemini, necesitamos actualizar nuestro servicio con una nueva función que reciba un archivo. Para ello agregaremos una nueva función llamada sendImage que reciba un archivo y devuelva una promesa con el resultado.:

async sendImage(file: File): Promise<string> {
}

Debemos usar un nuevo modelo, el gemini-pro-vision, el cual es un modelo que nos permitirá enviar imágenes. Para ello, moveremos la instancia de nuestro modelo dentro de cada función:

async sendPrompt(prompt: string): Promise<string> {
  const model = this.#genAI.getGenerativeModel({ model: 'gemini-pro' });

  try {
    const { response } = await model.generateContent(prompt);
    return response.text();
  } catch (error) {
    console.error(error);
    return 'An error has occurred. Please try again.';
  }
}

async sendImage(file: File): Promise<string> {
  const model = this.#genAI.getGenerativeModel({
    model: 'gemini-pro-vision',
  });
}

El modelo recibe un dato de tipo Part, así que debemos convertir nuestro archio a este tipo de dato:

async sendImage(file: File): Promise<string> {
  const model = this.#genAI.getGenerativeModel({
    model: 'gemini-pro-vision',
  });
  const part = await this.convertFileToGenerativePart(file);
}

async convertFileToGenerativePart(file: File): Promise<Part> {
  const base64EncodedDataPromise = new Promise<string>((resolve) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve((reader.result as string).split(',')[1]);
    reader.readAsDataURL(file);
  });

  return {
    inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
  };
}

Para concluir, debemos enviar la imagen junto a un prompt al modelo, y asegurarnos de manejar cualquier error que pueda surgir:

async sendImage(file: File): Promise<string> {
  const model = this.#genAI.getGenerativeModel({
    model: 'gemini-pro-vision',
  });

  try {
    const part = await this.convertFileToGenerativePart(file);
    const prompt = '¿Qué es lo que ves en esta imagen?';
    const { response } = await model.generateContent([prompt, part]);

    return response.text();
  } catch (error) {
    console.error(error);
    return 'An error has occurred. Please try again.';
  }
}

Nuestro servicio debería lucir así:

import { Injectable } from '@angular/core';
import { GoogleGenerativeAI, Part } from '@google/generative-ai';

@Injectable({
  providedIn: 'root',
})
export class GeminiService {
  readonly #API_KEY = '<YOUR-API-KEY>';
  readonly #genAI = new GoogleGenerativeAI(this.#API_KEY);

  async sendPrompt(prompt: string): Promise<string> {
    const model = this.#genAI.getGenerativeModel({ model: 'gemini-pro' });

    try {
      const { response } = await model.generateContent(prompt);
      return response.text();
    } catch (error) {
      console.error(error);
      return 'An error has occurred. Please try again.';
    }
  }

  async sendImage(file: File): Promise<string> {
    const model = this.#genAI.getGenerativeModel({
      model: 'gemini-pro-vision',
    });

    try {
      const part = await this.convertFileToGenerativePart(file);
      const prompt = '¿Qué es lo que ves en esta imagen?';
      const { response } = await model.generateContent([prompt, part]);

      return response.text();
    } catch (error) {
      console.error(error);
      return 'An error has occurred. Please try again.';
    }
  }

  async convertFileToGenerativePart(file: File): Promise<Part> {
    const base64EncodedDataPromise = new Promise<string>((resolve) => {
      const reader = new FileReader();
      reader.onloadend = () => resolve((reader.result as string).split(',')[1]);
      reader.readAsDataURL(file);
    });

    return {
      inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
    };
  }
}

2. Enviar la imagen al modelo

Agregaremos un nuevo input en nuestro chat.component.html para que el usuario pueda enviar una imagen:

<input
  #fileInput
  type="file"
  accept="image/*"
  (change)="sendImageMessage(fileInput.files)"
/>

Podemos ver que cada que se selecciona un archivo, se llama a la función sendImageMessage con el archivo seleccionado, la cual debemos implementar en nuestro chat.component.ts:

sendImageMessage(files: FileList | null): void {
  if (!files) {
    return;
  }

  const file = files[0];

  this.#geminiService
    .sendImage(file)
    .then((response) => this.response.set(response));
}

Nuestra función valida si se seleccionó un archivo, y si es así, llama a nuestro servicio para enviar la imagen y mostrar la respuesta en nuestro chat.

3. Mostrar la imagen

Ya por último, debemos mostrar la imagen en nuestro chat.component.html:

<img *ngIf="imageSrc()" [src]="imageSrc()" />

Estamos asumiendo que existe un signal imageSrc que contiene la URL de la imagen. Para ello, debemos agregarlo a nuestro chat.component.ts:

imageSrc = signal('');

Y actualizar nuestra función sendImageMessage para que guarde la URL de la imagen en nuestro signal:

sendImageMessage(files: FileList | null): void {
  if (!files) {
    return;
  }

  const file = files[0];
  this.imageSrc.set(URL.createObjectURL(file));

  this.#geminiService
    .sendImage(file)
    .then((response) => this.response.set(response));
}

Con estos cambios, ya deberíamos poder enviar imágenes a nuestro modelo de Gemini y mostrar la respuesta en nuestro chat.

Pasar logo de Angular a Gemini

¡Y eso es todo! Espero que este tutorial te haya sido de ayuda. Si tienes alguna duda, no dudes en contactarme.

...



📌 Angular + Gemini Pro Vision


📈 32.03 Punkte

📌 Google-Entwicklerkonferenz I/O: Gemini, Gemini, Gemini


📈 30.32 Punkte

📌 Google Bard: Die Gemini Ära beginnt schon heute – der KI-ChatBot basiert jetzt auf Gemini Pro (Englisch)


📈 23.24 Punkte

📌 Build with Gemini: Developers can now access Google Gemini Pro for free


📈 23.24 Punkte

📌 Google finally catches up with OpenAI, announces general availability of Gemini 1.0 Pro and Gemini 1.0 Ultra


📈 23.24 Punkte

📌 Gemini Update: Integration in viele Google-Produkte, Hey Gemini, Pixel 8-Debakel, Pixel Buds Pro 2 und mehr


📈 23.24 Punkte

📌 Tune Gemini Pro in Google AI Studio or with the Gemini API


📈 23.24 Punkte

📌 Google rebrands Duet AI for Devs as Gemini Code Assist, moving to Gemini 1.5 Pro


📈 23.24 Punkte

📌 Tune Gemini Pro in Google AI Studio or with the Gemini API


📈 23.24 Punkte

📌 Google is rolling out a new side panel using Gemini 1.5 Pro in Workspace #GoogleIO #AI #Gemini


📈 23.24 Punkte

📌 Gemini & Google Workspace: Neue KI-Features kommen – Update auf Gemini Pro 1.5 wird ausgerollt (Galerie)


📈 23.24 Punkte

📌 How To Use New Google Gemini 1.5 Pro (Gemini AI Tutorial) Complete Guide With Tips and Tricks


📈 23.24 Punkte

📌 Angular + Gemini


📈 21.73 Punkte

📌 Getting started with Google's Multi-modal "Gemini Pro Vision" LLM with Javascript for Beginners


📈 20.4 Punkte

📌 GOOGLE GEMINI PRO VISION VS OPENAI GPT4V WINNER REVEALED | TECH NEWS


📈 20.4 Punkte

📌 Image based Function Calling with gemini-1.0-pro-vision


📈 20.4 Punkte

📌 Gemini Pro vs GPT4V: OpenAI + Google Top 7 AI Vision, IQ Test Comparison (52 ROBOTS, 6650 TASKS)


📈 20.4 Punkte

📌 Benchmark suggests Phi-3-vision is on-par with Claude 3-haiku & Gemini 1.0 Pro, if not better


📈 20.4 Punkte

📌 Using Gemini Pro Vision for multimodal use cases with text, images, and videos


📈 20.4 Punkte

📌 gmitohtml - Gemini to HTML proxy (Gemini is a protocol similar to Finger and Gopher)


📈 20.21 Punkte

📌 Bard is now Gemini ✨ Chat with Gemini to supercharge your ideas, write, learn, plan and more


📈 20.21 Punkte

📌 Gemini-App im Test: Taugt Googles KI-App Gemini als Sprachassistent?


📈 20.21 Punkte

📌 Imagination ➡️ images 🖼️ Try Gemini image generation and #ChatWithGemini at gemini.google.com.


📈 20.21 Punkte

📌 Gemini Ultra vs GPT 4: How Google Gemini beats OpenAI GPT-4 in most benchmarks


📈 20.21 Punkte

📌 Gemini: Googles riesiges Update kommt am Mittwoch – Android-App, Gemini Advanced, Bard-Update und mehr


📈 20.21 Punkte

📌 Bard wird zu Gemini: Googles riesiges Update ist da – Android-App, Gemini Advanced, Bard-Upgrade und mehr


📈 20.21 Punkte

📌 Google renames Bard, launches Gemini Advanced offering, and announces new Gemini app for Android and iOS


📈 20.21 Punkte

📌 Gemini Advanced & Google One: Das ist das neue KI-Abo – bringt Gemini Ultra und weitere Vorteile (Video)


📈 20.21 Punkte

📌 This is Google Gemini! What do you think about it? #shorts #Google #Gemini #tech #phone #viral


📈 20.21 Punkte

📌 I asked Gemini and GPT-4 to explain deep learning AI, and Gemini won hands down


📈 20.21 Punkte

📌 Google rebrands Duet AI for Devs as Gemini Code Assist, moving from Codey to Gemini 1.5


📈 20.21 Punkte

📌 Oficial! Gemini Google AI Dart/Flutter SDK— Integrando Flutter com o GEMINI


📈 20.21 Punkte

📌 Googles neues KI-Modell: Warum heißt Gemini eigentlich Gemini?


📈 20.21 Punkte

📌 Gemini Advanced & Google One: Gemini Ultra gibt es nur im Abo – ist es mit 21,99 Euro zu teuer? (Meinung)


📈 20.21 Punkte











matomo