반응형
Hugging Face 에서 제공하는 pipelines는 간편하게 AI를 무료로 이용할 수 있는 기능을 제공한다. 고수준의 라이브러리 단 몇줄로 AI를 활용할 수 있다. 여기에서는 어떻게 이용할 수 있는지 설치 부터 대표적인 이용 방법을 정리해본다.
1. 라이브러리 설치
!pip install -q --upgrade torch==2.5.1+cu124 torchvision==0.20.1+cu124 torchaudio==2.5.1+cu124 --index-url https://download.pytorch.org/whl/cu124
!pip install -q --upgrade transformers==4.48.3 datasets==3.2.0 diffusers
- 최신 버전의 PyTorch 및 관련 라이브러리 설치 (cu124는 CUDA 12.4 버전용).
- Hugging Face의 transformers, datasets, diffusers 라이브러리 설치.
2. 라이브러리 임포트
import torch
from google.colab import userdata
from huggingface_hub import login
from transformers import pipeline
from diffusers import DiffusionPipeline
from datasets import load_dataset
import soundfile as sf
from IPython.display import Audio
- 필요한 라이브러리들을 불러옵니다.
- userdata: Colab에서 사용자 토큰을 안전하게 불러오기 위해 사용.
- pipeline: Hugging Face의 다양한 작업을 쉽게 수행할 수 있는 API.
3. Hugging Face 로그인
hf_token = userdata.get('HF_TOKEN')
login(hf_token, add_to_git_credential=True)
- Hugging Face 토큰을 불러와 로그인합니다.
- 모델 다운로드 및 사용 권한을 위해 필요합니다.
이제부터는 이용방법들이다.
감정 분석 (Sentiment Analysis)
# Sentiment Analysis
classifier = pipeline("sentiment-analysis", device="cuda")
result = classifier("I'm excited!")
print(result)
- 문장의 감정을 분석합니다 (긍정/부정).
- GPU를 사용하여 빠르게 처리.
개체명 인식 (Named Entity Recognition)
# Named Entity Recognition
ner = pipeline("ner", grouped_entities=True, device="cuda")
result = ner("My name is Wolfgang and I live in Berlin")
print(result)
- 문장에서 사람, 장소, 조직 등의 개체를 인식합니다.
질문 응답 (Question Answering)
# Question Answering with Context
question_answerer = pipeline("question-answering", device="cuda")
result = question_answerer(question="Who was the 42th president of the United States?", context="Barack Obama was the 44th president of the United States.")
print(result)
- 주어진 문맥을 기반으로 질문에 답변합니다.
요약 (Summarization)
# Text Summarization
summarizer = pipeline("summarization", device="cuda")
text = """Question answering tasks return an answer given a question. If you’ve ever asked a virtual assistant like Alexa, Siri or Google what the weather is, then you’ve used a question answering model before. There are two common types of question answering tasks
"""
summary = summarizer(text, max_length=50, min_length=25, do_sample=False)
print(summary[0]['summary_text'])
- 긴 텍스트를 간결하게 요약합니다.
제로샷 분류 (Zero-shot Classification)
# Classification
classifier = pipeline("zero-shot-classification", device="cuda")
result = classifier("Hugging Face's is amazing!", candidate_labels=["technology", "sports", "politics"])
print(result)
- 사전 학습 없이 문장을 주어진 카테고리 중 하나로 분류.
텍스트 생성 (Text Generation)
# Text Generation
generator = pipeline("text-generation", device="cuda")
result = generator("If there's one thing I want you to remember about using HuggingFace pipelines, it's")
print(result[0]['generated_text'])
- 주어진 문장을 기반으로 이어지는 텍스트 생성.
이미지 생성 (Text-to-Image)
# Image Generation
image_gen = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-2",
torch_dtype=torch.float16,
use_safetensors=True,
variant="fp16"
).to("cuda")
text = "Children wearing security T-shirts are having fun studying in the classroom. Cartoon style."
image = image_gen(prompt=text).images[0]
image
- 텍스트를 기반으로 이미지를 생성 (Stable Diffusion 사용).
음성 생성 (Text-to-Speech)
# Audio Generation
synthesiser = pipeline("text-to-speech", "microsoft/speecht5_tts", device='cuda')
embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
speaker_embedding = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0)
speech = synthesiser("Children wearing Best of Best T-shirts are having fun studying in the classroom. ", forward_params={"speaker_embeddings": speaker_embedding})
sf.write("speech.wav", speech["audio"], samplerate=speech["sampling_rate"])
Audio("speech.wav")
- 텍스트를 음성으로 변환.
- 특정 화자의 음색을 반영하기 위해 xvector 임베딩 사용
반응형
'Bigdata' 카테고리의 다른 글
AI/LLM 모델 성능을 비교 평가하는 주요 리더보드 정리 (2) | 2025.08.06 |
---|---|
WebDancer? - Aliexpress 에서 진행하는 자율적인 정보 탐색 에이전트 논문 요약 (3) | 2025.08.01 |
데이터베이스에서 UUID 사용의 주요 문제점 (0) | 2025.07.10 |
LangChain Messages 역활 (0) | 2025.06.10 |
LLM - LoRA 파인튜닝 쉽게 이해하기 (0) | 2025.06.09 |