0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

HuggingFaceでGradio製のアプリを展開する

Last updated at Posted at 2025-02-10

はじめに

最近では、ちょっと思いついたアプリケーションなどについて
difyなどを活用しながらAIのアプリを作っていく流れが一般的になりつつあるかと思います。
RAGを活用したチャットなどのユースケースでは十分ですが、もう少しプログラムを書いて、AIを活用したゲームを動かしてみたい!などのユースケースの場合は、difyに加えて、アプリケーションサーバーなど別途用意する必要が出てきます。
そのような中で、HuggingFaceのSpaceを最近、使い始めていますが、
とても便利です。また、Gradioという仕組みを用いることで必要最低限のことを記述するだけでAI関連の仕組みをWebアプリとして動かすことが可能となります。

HuggingFaceでは、AI-Game-Jamのようなイベントも行われているようで、Gradioで作られたアプリケーションなどが紹介されていました。

IMG_0364.jpeg

使い方

1.Githubのcodespaceを使って立ち上げる。

2. インストール

IMG_0368.jpeg

$ pip install gradio
$ touch app.py

デモのコードを記述

fn ... UIと連携する関数
inputs ... 入力コンポーネント
outpus ... 出力コンポーネント

import gradio as gr

def greet(name):
    return "Hello " + name + "!"

demo = gr.Interface(fn=greet, inputs="text", outputs="text")

demo.launch()

IMG_0367.jpeg

実行

$ python app.py

IMG_0366.jpeg

画像アプリを作る

Gradioでは、gr.Image()を使うことで、画像アップロード画面がアプリケーションで表示される。下記コードでは画像フィルタをかけるサンプル。

import numpy as np
import gradio as gr

def sepia(input_img):
    sepia_filter = np.array([
        [0.393, 0.769, 0.189],
        [0.349, 0.686, 0.168],
        [0.272, 0.534, 0.131]
    ])
    sepia_img = input_img.dot(sepia_filter.T)
    sepia_img /= sepia_img.max()
    return sepia_img

demo = gr.Interface(sepia, gr.Image(), "image")
demo.launch()

IMG_0370.jpeg

IMG_0371.jpeg

複数のステップによる実行を行う事例

from transformers import pipeline

import gradio as gr

asr = pipeline("automatic-speech-recognition", "facebook/wav2vec2-base-960h")
classifier = pipeline("text-classification")


demo.launch()

チャットぼっと

python app.py
import gradio as gr
from openai import OpenAI

OPENAI_API_KEY="自分のAPIキーを入力"
client = OpenAI(api_key=OPENAI_API_KEY)

def chatbot_response(message, history):
    messages = []
    if len(history) > 6:
        history = history[2:]
    for h in history:
        messages.append({"role": "user", "content": h[0]})
        messages.append({"role": "assistant", "content": h[1]})
    messages.append({"role": "user", "content": message})
    completion = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=messages,
    )
    return completion.choices[0].message.content

app = gr.ChatInterface(chatbot_response)
app.launch()

HuggingFace側で作成する

LLMを活用したチャットぼっとなどはHuggingFaceでテンプレートが用意されているため、こちらを実行することでも実装が可能です。

1.

IMG_0360.jpeg

2.

IMG_0361.jpeg

3.

IMG_0363.jpeg

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?