이번 강의에서는 Google Cloud Functions와 Vision API를 활용하여 Cloud Storage에 업로드된 이미지에서 텍스트를 추출하고, 추출된 텍스트를 BigQuery에 저장하는 방법을 배우게 됩니다.
Cloud Storage 버킷에 파일이 업로드될 때 트리거되는 Cloud Function을 생성합니다.
requirements.txt
functions-framework==3.*
google-cloud-vision==0.36.0
google-cloud-bigquery==1.11.2
six==1.16.0
main.py
from google.cloud import vision_v1
from google.cloud import bigquery
from google.api_core import exceptions
import functions_framework
@functions_framework.cloud_event
def hello_gcs(cloud_event):
try:
data = cloud_event.data
event_id = cloud_event["id"]
event_type = cloud_event["type"]
bucket = data["bucket"]
name = data["name"]
metageneration = data["metageneration"]
timeCreated = data["timeCreated"]
updated = data["updated"]
print(f"Event ID: {event_id}")
print(f"Event type: {event_type}")
print(f"Bucket: {bucket}")
print(f"File: {name}")
print(f"Metageneration: {metageneration}")
print(f"Created: {timeCreated}")
print(f"Updated: {updated}")
# GCS URI 생성
gcs_uri = f"gs://{bucket}/{name}"
print(f"GCS URI: {gcs_uri}")
detect_text(gcs_uri)
except Exception as e:
print(f"Error in hello_gcs function: {e}")
def detect_text(gcs_uri):
try:
print("Initializing Vision and BigQuery clients.")
vision_client = vision_v1.ImageAnnotatorClient()
bigquery_client = bigquery.Client()
print(f"Creating Image object for {gcs_uri}")
image = vision_v1.types.Image()
image.source.image_uri = gcs_uri
print(f"Image object created: {image}")
print("Calling text_detection on Vision API.")
response = vision_client.text_detection(image=image)
texts = response.text_annotations
extracted_text = texts[0].description if texts else ""
print(f"Extracted text: {extracted_text}")
print("Preparing BigQuery insert query.")
query = """
INSERT INTO `your_project_id.your_dataset.your_table` (image, text)
VALUES (@image, @text)
"""
job_config = bigquery.QueryJobConfig(
query_parameters=[
bigquery.ScalarQueryParameter("image", "STRING", gcs_uri),
bigquery.ScalarQueryParameter("text", "STRING", extracted_text),
]
)
print("Executing BigQuery insert query.")
query_job = bigquery_client.query(query, job_config=job_config)
query_job.result() # Wait for the job to complete
print("Text detection and insertion complete.")
except exceptions.GoogleAPICallError as api_error:
print(f"Google API call error: {api_error}")
except exceptions.RetryError as retry_error:
print(f"Retry error: {retry_error}")
except exceptions.ClientError as client_error:
print(f"Client error: {client_error}")
except Exception as e:
print(f"Unexpected error in detect_text function: {e}")
Google Cloud Console에서 Cloud Storage 버킷을 생성하고, 이 버킷에 파일을 업로드할 때 Cloud Function이 트리거되도록 설정합니다.
Google Cloud Console에서 BigQuery 테이블을 생성하고, 테이블 스키마를 다음과 같이 설정합니다:
Cloud Function을 배포하고, Cloud Storage에 이미지를 업로드하여 기능을 테스트합니다.
로그를 확인하여 텍스트 추출 및 BigQuery 저장이 정상적으로 수행되는지 확인합니다.
이번 강의를 통해 Google Cloud Functions와 Vision API를 활용하여 이미지에서 텍스트를 추출하고, BigQuery에 데이터를 저장하는 전체 과정을 이해하게 됩니다. 이를 통해 서버리스 아키텍처와 클라우드 서비스를 효과적으로 활용하는 방법을 배울 수 있습니다.
Nginx에서 HTTPS 및 에러 로그 설정하기 (0) | 2024.05.06 |
---|---|
[RHEL9] Docker에 dart_frog 빌드 후 Nginx 가상호스트 지정까지 (0) | 2024.04.24 |
[CentOS] SSL 인증서 발급 후 httpd 재시작 에러 해결하기 (0) | 2023.07.01 |