2025. 3. 18. 21:35ㆍAI/AI
📌 AI API 실습 프로젝트: 최신 API 반영 및 실전 적용
이번 실습 프로젝트에서는 Google Vision AI, Google Speech-to-Text API, OpenAI API, Google Dialogflow를 활용하여 이미지 분류기, 음성 감정 분석기, AI 챗봇을 구축한다.
최신 API 변경 사항을 반영하여 보다 안정적이고 확장 가능한 AI 애플리케이션을 개발하는 방법을 익힌다.
🔹 1️⃣ 프로젝트 1: 이미지 분류기 만들기 (Google Vision AI + Python)
✅ 프로젝트 개요
Google Vision AI를 활용하여 이미지를 분석하고, 객체를 자동으로 분류하는 AI 모델을 구현한다.
이 모델은 상품 이미지, 동물, 음식, 사물 등 다양한 항목을 자동으로 분류하는 기능을 수행할 수 있다.
📌 Google Vision AI API 설정 및 사용 방법
✅ 1. 최신 Google Cloud Vision API 문서 확인 → 공식 문서
✅ 2. 서비스 계정 키(JSON) 생성 및 환경 변수 설정
✅ 3. Python을 사용하여 API 호출 및 이미지 분석
📌 이미지 분류기 코드 예제 (Google Vision AI 활용)
from google.cloud import vision
import os
import time
# 서비스 계정 인증 설정 (환경 변수 사용)
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "your-vision-service-account.json"
# Vision API 클라이언트 생성
client = vision.ImageAnnotatorClient()
def classify_image(image_path, retries=3):
"""Google Vision AI를 사용한 이미지 분류 및 오류 처리"""
with open(image_path, "rb") as image_file:
content = image_file.read()
image = vision.Image(content=content)
for attempt in range(retries):
try:
response = client.label_detection(image=image)
return response
except Exception as e:
print(f"⚠️ API 호출 오류 발생: {e}")
if attempt < retries - 1:
print(f"재시도 중... ({attempt + 1}/{retries})")
time.sleep(2)
else:
print("❌ 최대 재시도 횟수 초과, 요청 실패")
return None
# 실행 예제
response = classify_image("sample_image.jpg")
if response:
print("🔹 이미지 분류 결과:")
for label in response.label_annotations:
print(f"- {label.description} (신뢰도: {label.score:.2f})")
🔹 2️⃣ 프로젝트 2: 음성 감정 분석기 만들기 (Speech-to-Text API + 감정 분석 API)
✅ 프로젝트 개요
음성을 텍스트로 변환한 후, 텍스트의 감정을 분석하여 긍정/부정/중립을 분류하는 AI 시스템을 구축한다.
이를 통해 AI 기반 고객 피드백 분석, 콜센터 감정 분석, 감성 기반 음성 인터페이스 구축 등에 활용할 수 있다.
📌 API 설정 및 사용 방법
✅ 1. 최신 Google Speech-to-Text API 문서 확인 → 공식 문서
✅ 2. OpenAI GPT-4 API 또는 Google Natural Language API 활용하여 감정 분석
📌 음성 감정 분석기 코드 예제 (최신 OpenAI API 적용)
from google.cloud import speech
import openai
import os
import time
# API 인증 정보 설정
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "your-speech-service-account.json"
speech_client = speech.SpeechClient()
def transcribe_audio(file_path, retries=3):
"""음성을 텍스트로 변환하는 함수"""
with open(file_path, "rb") as audio_file:
content = audio_file.read()
audio = speech.RecognitionAudio(content=content)
config = speech.RecognitionConfig(
encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=16000,
language_code="ko-KR"
)
for attempt in range(retries):
try:
response = speech_client.recognize(config=config, audio=audio)
return response
except Exception as e:
print(f"⚠️ API 호출 오류 발생: {e}")
if attempt < retries - 1:
time.sleep(2)
else:
print("❌ 요청 실패")
return None
# 실행 예제
speech_response = transcribe_audio("sample_audio.wav")
if speech_response:
recognized_text = speech_response.results[0].alternatives[0].transcript
print(f"🎙️ 변환된 텍스트: {recognized_text}")
# 감정 분석 (최신 OpenAI API 반영)
openai.api_key = "your-openai-api-key"
sentiment_response = openai.chat.completions.create(
model="gpt-4",
messages=[{"role": "system", "content": "Analyze the sentiment of the given text."},
{"role": "user", "content": recognized_text}]
)
print("🔹 감정 분석 결과:", sentiment_response.choices[0].message.content)
🔹 3️⃣ 프로젝트 3: AI 챗봇 만들기 (Google Dialogflow 활용)
✅ 프로젝트 개요
Google Dialogflow를 활용하여 사용자의 입력을 이해하고, 자동으로 응답하는 AI 챗봇을 구축한다.
이를 통해 고객 지원 챗봇, FAQ 자동 응답 시스템, 음성 기반 AI 비서 등을 개발할 수 있다.
📌 Google Dialogflow API 설정 및 사용 방법
✅ 1. 최신 Google Dialogflow 문서 확인 → 공식 문서
✅ 2. Intent(사용자 의도) 및 Training Phrases 설정
✅ 3. API를 통해 챗봇과 연동하여 응답 받기
📌 AI 챗봇 API 연동 코드 예제 (Python)
from google.cloud import dialogflow
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "your-dialogflow-service-account.json"
client = dialogflow.SessionsClient()
session_id = "test-session"
session = f"projects/your-project-id/agent/sessions/{session_id}"
user_message = "안녕하세요! 이 서비스는 무엇을 할 수 있나요?"
text_input = dialogflow.TextInput(text=user_message, language_code="ko")
query_input = dialogflow.QueryInput(text=text_input)
response = client.detect_intent(session=session, query_input=query_input)
print("🤖 챗봇 응답:", response.query_result.fulfillment_text)
'AI > AI' 카테고리의 다른 글
Cloud AI - 4. 클라우드 AI의 확장과 실무 적용 (MLOps 개념 이해) (0) | 2025.03.18 |
---|---|
Cloud AI - 4. 클라우드 AI의 확장과 실무 적용 (데이터 엔지니어링과 AI) (0) | 2025.03.18 |
Cloud AI - 3. 클라우드 AI 활용 프로젝트 (AI API 연동 및 결과 분석) (0) | 2025.03.18 |
Cloud AI - 3. 클라우드 AI 활용 프로젝트 (데이터 수집 및 전처리) (0) | 2025.03.18 |
Cloud AI - 3. 클라우드 AI 활용 프로젝트 (프로젝트 기획 및 아이디어 선정) (0) | 2025.03.18 |