CodeGym /행동 /Python SELF KO /AI API 다루기

AI API 다루기

Python SELF KO
레벨 24 , 레슨 4
사용 가능

10.1 ChatGPT

잠깐, 무슨 말인지 모르겠어? 우리 지금 인공지능 시대에 살고 있잖아. 이걸 한번 다뤄보자. 물론 ChatGPT부터 시작해야지.

OpenAI API (ChatGPT) 사용 예시

OpenAI API를 사용하려면 플랫폼에 등록하고 API 키를 받아서 요청을 보낼 때 인증에 사용해야 해.

먼저 openai 라이브러리를 설치해야 해 — 이건 공식 클라이언트야.


pip install openai

이제 어떤 요청을 보내볼까:


import openai

# 너의 OpenAI API 키
api_key = 'YOUR_OPENAI_API_KEY'

# 인증
openai.api_key = api_key

# ChatGPT 모델에 요청
response = openai.Completion.create(
    engine="text-davinci-003",
    prompt="우주에 대한 흥미로운 사실을 말해줘.",
    max_tokens=500
)

# 응답 출력
print(response.choices[0].text.strip())

공식 웹사이트에 등록해서 키를 받아야 해. 새로운 사용자라면 (전화번호가 데이터베이스에 없으면), 무료로 $20를 받을 수 있어.

10.2 Google Cloud Vision API

Google Cloud Vision API는 객체, 텍스트, 얼굴 및 기타 요소를 인식하는 이미지 분석 기능을 제공해. 지금 Google Bard API는 공개되어 있지 않고, Google Cloud Platform을 통해 인증이 필요해.

1단계. 먼저 google-cloud-vision 라이브러리를 설치해.


pip install google-cloud-vision

2단계. 서비스 계정 키를 사용하여 인증을 설정해.

이미지 분석 예제 코드:


from google.cloud import vision
import io

# 클라이언트 초기화
client = vision.ImageAnnotatorClient()

# 이미지 로드
file_name = 'path/to/your/image.jpg'
with io.open(file_name, 'rb') as image_file:
    content = image_file.read()

image = vision.Image(content=content)

# 객체 인식
response = client.object_localization(image=image)
objects = response.localized_object_annotations

# 발견된 객체 출력
for object_ in objects:
    print(f'Object name: {object_.name}')
    print(f'Score: {object_.score}') 

이 코드는 이미지를 인식해서 그 안에 있는 객체들의 목록을 보여줘. 프로젝트에 쉽게 추가해서 멋진 웹 서비스나 앱을 만들 수 있어.

10.3 Microsoft Text Analytics API

Azure Cognitive Services는 언어 감지, 감정 분석, 키워드 추출 및 개체 인식을 포함한 텍스트 분석 API를 제공해.

텍스트 감정 분석은 텍스트의 감정적 색채(긍정적, 부정적 또는 중립적)를 파악하는 프로세스야. 이건 고객 후기 분석, 소셜 미디어 모니터링 또는 특정 이벤트나 제품에 대한 반응을 평가하는 데 유용할 수 있어.

라이브러리 설치 및 인증

1단계. Azure 라이브러리를 설치해:


pip install azure-ai-textanalytics

2단계. API 키와 (endpoint) 끝점을 사용해 인증을 설정해.

텍스트 감정 분석 예제 코드:


from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

# 클라이언트 초기화
endpoint = "YOUR_AZURE_ENDPOINT"
api_key = "YOUR_AZURE_API_KEY"
credential = AzureKeyCredential(api_key)
client = TextAnalyticsClient(endpoint=endpoint, credential=credential)

# 분석할 텍스트
documents = ["I love programming in Python!", "I'm feeling very happy today!"]

# 감정 분석
response = client.analyze_sentiment(documents=documents)

# 결과 출력
for doc in response:
    print(f"Sentiment: {doc.sentiment}")
    print(f"Confidence Scores: {doc.confidence_scores}")

10.4 DeepAI (Text Summarization API)

DeepAI는 텍스트 요약을 포함하여 다양한 머신러닝 작업을 위한 API를 제공해.

텍스트 요약은 긴 텍스트의 핵심 아이디어와 주요 내용을 유지하면서 짧은 요약을 만드는 과정이야. 긴 문서를 빨리 살펴보거나 자동으로 주석을 작성하거나 대량의 텍스트 정보를 처리하는 데 유용해.

라이브러리 설치 및 인증

1단계. requests 라이브러리를 설치해:


pip install requests

2단계. API 키를 사용해 인증해.

텍스트 요약 예제 코드:


import requests

# 너의 API 키 DeepAI
api_key = 'YOUR_DEEPAI_API_KEY'

# 요약할 텍스트
text = "Artificial intelligence (AI) is intelligence demonstrated by machines, in contrast to the natural intelligence displayed by humans and animals. Leading AI textbooks define the field as the study of 'intelligent agents': any device that perceives its environment and takes actions that maximize its chance of successfully achieving its goals."

# API 요청
response = requests.post(
    "https://api.deepai.org/api/summarization",
    data={'text': text},
    headers={'api-key': api_key}
)

# 응답 받기
data = response.json()

# 요약 출력
print(data['output'])

가능한 출력

위의 코드를 올바른 API 키로 실행하면 다음과 비슷한 결과를 얻을 수 있어:


Artificial intelligence (AI) is the intelligence shown by machines, unlike natural intelligence in humans and 
animals. AI studies 'intelligent agents': devices that perceive their environment and act to achieve their 
goals.

이 요약은 원본 텍스트의 주요 내용을 포함하면서 더 짧은 버전으로 줄여줘. 알고리즘이나 DeepAI에서 사용되는 모델 버전에 따라 정확한 결과는 다를 수 있어.

1
설문조사/퀴즈
네트워크 작업, 레벨 24, 레슨 4
사용 불가능
네트워크 작업
네트워크 작업
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION