Hệ thống DanQing AI, một sự kết hợp tinh tế giữa công nghệ học sâu và mỹ học phương Đông, cung cấp khả năng hiểu biết hình ảnh thông minh. Không chỉ dừng lại ở việc nhận diện chính xác nội dung ảnh, nó còn tạo ra những mô tả văn học hóa theo phong cách thư pháp và thủy mặc truyền thống, thổi hồn nghệ thuật vào các sản phẩm số.
Những điểm nổi bật của DanQing AI, khác biệt so với các công cụ nhận dạng hình ảnh thông thường, bao gồm:
- Năng lực hiểu biết ngữ nghĩa sâu sắc: Sử dụng nền tảng hiểu biết đa phương thức OFA để nhận diện chủ thể, hành động và cảm xúc trong hình ảnh.
- Trình bày mang tính nghệ thuật cao: Kết quả phân tích được hiển thị trực quan thông qua các nét thư pháp (hành, thảo) động, tựa như lời đề từ của một danh họa.
- Trải nghiệm văn hóa đậm nét: Giao diện người dùng tối giản với tông màu thủy mặc, lấy cảm hứng từ giấy tuyên cổ và con dấu chu sa, tạo cảm giác đắm chìm.
DanQing AI là giải pháp lý tưởng cho các ứng dụng đòi hỏi nâng cao giá trị văn hóa và trải nghiệm người dùng, chẳng hạn như triển lãm số, thương hiệu văn hóa-sáng tạo, cá nhân hóa quà tặng, và sản xuất nội dung.
Truy cập API và cấu hình kiểm soát lưu lượng
Phương pháp gọi API cơ bản
DanQing AI cung cấp giao diện API RESTful đơn giản, cho phép bạn dễ dàng thực hiện phân tích hình ảnh và tạo mô tả nghệ thuật chỉ với vài dòng mã:
import requests
import base64
import json
# Cấu hình điểm cuối dịch vụ và khóa API
SERVICE_ENDPOINT = "https://api.danqing.com/v1/analyze"
AUTH_KEY = "YOUR_API_KEY_HERE"
def convert_image_to_base64(file_path: str) -> str:
"""Mã hóa tệp hình ảnh thành chuỗi base64."""
with open(file_path, "rb") as img_file:
return base64.b64encode(img_file.read()).decode('utf-8')
def call_image_analysis_api(input_image_path: str, lang_style: str = "cursive") -> dict:
"""
Gửi yêu cầu phân tích hình ảnh đến API của DanQing AI.
:param input_image_path: Đường dẫn đến tệp hình ảnh đầu vào.
:param lang_style: Phong cách thư pháp mong muốn (e.g., 'cursive', 'regular').
:return: Kết quả phân tích dưới dạng từ điển.
"""
api_headers = {
"Authorization": f"Bearer {AUTH_KEY}",
"Content-Type": "application/json"
}
request_payload = {
"imageData": convert_image_to_base64(input_image_path),
"renderingStyle": lang_style,
"outputFormat": "json",
"language": "vi"
}
try:
response = requests.post(SERVICE_ENDPOINT, headers=api_headers, json=request_payload)
response.raise_for_status() # Ném ngoại lệ cho các lỗi HTTP (4xx hoặc 5xx)
return response.json()
except requests.exceptions.RequestException as e:
print(f"Lỗi khi gọi API: {e}")
return {"error": str(e)}
# Ví dụ sử dụng API
image_file_to_process = "path/to/your/photo.jpg"
analysis_result = call_image_analysis_api(image_file_to_process, lang_style="regular")
if analysis_result and "description" in analysis_result:
print(analysis_result["description"])
else:
print("Không thể lấy mô tả hoặc có lỗi xảy ra.")
Chiến lược kiểm soát lưu lượng thông minh
Để đảm bảo sự ổn định và công bằng cho dịch vụ, API DanQing AI đã tích hợp các chiến lược giới hạn tốc độ nhiều cấp. Bạn có thể tùy chỉnh tần suất gọi API dựa trên yêu cầu kinh doanh của mình:
import time
import requests
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class DanQingAPIHandler:
"""
Quản lý các yêu cầu API đến dịch vụ DanQing, bao gồm giới hạn tốc độ và thử lại tự động.
"""
def __init__(self, api_key: str, max_retries_on_limit: int = 3, initial_backoff_delay: float = 1.0):
self.api_key = api_key
self.max_retries_on_limit = max_retries_on_limit
self.initial_backoff_delay = initial_backoff_delay
self._last_api_call_timestamp = 0.0
self._min_request_gap_seconds = 0.1 # Khoảng cách tối thiểu 100ms giữa các cuộc gọi
def _wait_for_cooldown(self):
"""Chờ đủ thời gian trước khi thực hiện cuộc gọi API tiếp theo."""
current_moment = time.time()
time_since_last_call = current_moment - self._last_api_call_timestamp
if time_since_last_call < self._min_request_gap_seconds:
time.sleep(self._min_request_gap_seconds - time_since_last_call)
self._last_api_call_timestamp = time.time()
def execute_with_rate_limit_and_retry(self, image_path: str, api_func: callable, **kwargs) -> dict:
"""
Thực hiện cuộc gọi API với cơ chế giới hạn tốc độ và thử lại theo chiến lược lùi mũ.
:param image_path: Đường dẫn tới hình ảnh cần xử lý.
:param api_func: Hàm API thực tế (ví dụ: call_image_analysis_api từ phần 2.1).
:param kwargs: Các đối số bổ sung để truyền tới api_func.
:return: Kết quả từ API hoặc thông báo lỗi.
"""
for attempt in range(self.max_retries_on_limit + 1):
self._wait_for_cooldown()
try:
response_data = api_func(image_path, **kwargs)
if "error" not in response_data:
return response_data
# Giả định lỗi giới hạn tốc độ sẽ có mã 429 hoặc thông báo cụ thể
if "429 Client Error" in response_data.get("error", "") or "Too Many Requests" in response_data.get("error", ""):
if attempt < self.max_retries_on_limit:
delay = self.initial_backoff_delay * (2 ** attempt)
logging.warning(f"Bị giới hạn tốc độ. Thử lại sau {delay:.2f} giây... (Lần {attempt + 1}/{self.max_retries_on_limit})")
time.sleep(delay)
else:
raise Exception("Đã vượt quá số lần thử lại tối đa do giới hạn tốc độ API.")
else:
raise Exception(response_data.get("error", "Lỗi API không xác định."))
except requests.exceptions.HTTPError as e:
if e.response.status_code == 429:
if attempt < self.max_retries_on_limit:
delay = self.initial_backoff_delay * (2 ** attempt)
logging.warning(f"Bị giới hạn tốc độ (HTTP 429). Thử lại sau {delay:.2f} giây... (Lần {attempt + 1}/{self.max_retries_on_limit})")
time.sleep(delay)
else:
raise Exception("Đã vượt quá số lần thử lại tối đa do giới hạn tốc độ API.")
else:
raise e
except Exception as e:
raise Exception(f"Lỗi không mong muốn trong khi gọi API: {e}")
raise Exception("Không thể hoàn thành yêu cầu sau nhiều lần thử lại.")
# Ví dụ sử dụng trình xử lý với giới hạn tốc độ
# Lưu ý: Hàm call_image_analysis_api phải được định nghĩa trước đó hoặc trong cùng phạm vi.
api_handler = DanQingAPIHandler("YOUR_API_KEY_HERE")
try:
processed_result = api_handler.execute_with_rate_limit_and_retry(
"path/to/another/photo.png",
call_image_analysis_api,
lang_style="cursive"
)
logging.info(f"Kết quả xử lý ảnh với giới hạn tốc độ: {processed_result.get('description', 'Không có mô tả.')}")
except Exception as e:
logging.error(f"Xử lý thất bại: {e}")
Các chính sách giới hạn tốc độ điển hình:
- Gói Cơ bản: 10 yêu cầu mỗi phút, tối đa 1.000 yêu cầu mỗi ngày.
- Gói Nâng cao: 60 yêu cầu mỗi phút, tối đa 10.000 yêu cầu mỗi ngày.
- Gói Doanh nghiệp: Cho phép cấu hình giới hạn tùy chỉnh và xử lý các đợt lưu lượng truy cập đột biến.
Nhúng hình mờ và bảo vệ bản quyền
Nhúng hình mờ số vô hình
DanQing AI hỗ trợ kỹ thuật hình mờ số vô hình (invisible digital watermark), giúp bảo vệ bản quyền mà không làm ảnh hưởng đến chất lượng hình ảnh hiển thị:
import cv2
import numpy as np
from PIL import Image # Giữ lại import này để nhất quán, mặc dù không dùng trực tiếp trong LSB
def embed_invisible_copyright_mark(source_image_path: str, destination_path: str, copyright_info: str) -> str:
"""
Nhúng thông tin bản quyền dưới dạng hình mờ số vô hình vào ảnh bằng kỹ thuật LSB (Least Significant Bit).
:param source_image_path: Đường dẫn đến ảnh gốc.
:param destination_path: Đường dẫn lưu ảnh đã nhúng hình mờ.
:param copyright_info: Chuỗi thông tin bản quyền cần nhúng.
:return: Đường dẫn đến ảnh đã được nhúng.
"""
original_image = cv2.imread(source_image_path)
if original_image is None:
raise FileNotFoundError(f"Không thể đọc ảnh từ đường dẫn: {source_image_path}")
# Chuyển thông tin bản quyền thành chuỗi bit
binary_message = ''.join(format(ord(char), '08b') for char in copyright_info)
binary_message += '1111111111111110' # Dấu hiệu kết thúc thông báo
# Lấy các kênh pixel ảnh và làm phẳng
image_pixels_flat = original_image.flatten()
if len(binary_message) > len(image_pixels_flat):
raise ValueError("Thông tin bản quyền quá dài để nhúng vào ảnh này.")
# Nhúng từng bit của thông báo vào bit cuối cùng (LSB) của từng pixel
for pixel_idx in range(len(binary_message)):
current_bit = int(binary_message[pixel_idx])
image_pixels_flat[pixel_idx] = (image_pixels_flat[pixel_idx] & 0xFE) | current_bit
# Khôi phục ảnh từ mảng pixel đã làm phẳng
watermarked_image_array = image_pixels_flat.reshape(original_image.shape)
cv2.imwrite(destination_path, watermarked_image_array)
return destination_path
# Ví dụ thực hiện
output_with_invisible_mark = embed_invisible_copyright_mark(
"input.jpg",
"output_invisible_watermark.jpg",
"Bản quyền © 2024 DanQing AI. Mọi quyền được bảo lưu."
)
# print(f"Ảnh với hình mờ vô hình đã lưu tại: {output_with_invisible_mark}")
Thêm thông tin bản quyền hiển thị
Bên cạnh hình mờ vô hình, hệ thống còn hỗ trợ thêm thông tin bản quyền hiển thị một cách nghệ thuật:
from PIL import Image, ImageDraw, ImageFont
import os
def apply_visual_watermark_text(input_file: str, output_file: str, watermark_caption: str) -> str:
"""
Thêm thông tin bản quyền hiển thị rõ ràng với phong cách nghệ thuật vào ảnh.
:param input_file: Đường dẫn đến ảnh đầu vào.
:param output_file: Đường dẫn để lưu ảnh đã thêm hình mờ.
:param watermark_caption: Chuỗi văn bản bản quyền.
:return: Đường dẫn đến ảnh đã được thêm hình mờ.
"""
try:
pil_image = Image.open(input_file).convert("RGBA")
except FileNotFoundError:
raise FileNotFoundError(f"Không tìm thấy tệp ảnh: {input_file}")
except Exception as e:
raise ValueError(f"Không thể mở hoặc xử lý ảnh: {e}")
drawing_context = ImageDraw.Draw(pil_image)
# Cố gắng tải một font phù hợp hoặc sử dụng font mặc định
font_size = 24
try:
font_path = "arial.ttf" # Cần đảm bảo font này có sẵn trên hệ thống
if not os.path.exists(font_path):
font = ImageFont.load_default()
else:
font = ImageFont.truetype(font_path, font_size)
except Exception:
font = ImageFont.load_default()
img_width, img_height = pil_image.size
text_length = drawing_context.textlength(watermark_caption, font=font)
estimated_text_height = font_size * 1.2 # Ước tính chiều cao văn bản
# Đặt vị trí văn bản ở góc dưới bên phải, có đệm
padding_x = 15
padding_y = 15
position_x = img_width - text_length - padding_x
position_y = img_height - estimated_text_height - padding_y
# Tạo một lớp phủ bán trong suốt cho nền văn bản
overlay = Image.new('RGBA', pil_image.size, (255,255,255,0))
overlay_draw = ImageDraw.Draw(overlay)
bg_x1 = max(0, position_x - padding_x)
bg_y1 = max(0, position_y - padding_y)
bg_x2 = min(img_width, position_x + text_length + padding_x)
bg_y2 = min(img_height, position_y + estimated_text_height + padding_y)
overlay_draw.rectangle([bg_x1, bg_y1, bg_x2, bg_y2], fill=(0, 0, 0, 120))
pil_image = Image.alpha_composite(pil_image, overlay)
drawing_context = ImageDraw.Draw(pil_image)
drawing_context.text((position_x, position_y), watermark_caption, font=font, fill=(255, 255, 255, 255))
if pil_image.mode == 'RGBA':
pil_image = pil_image.convert('RGB')
pil_image.save(output_file)
return output_file
# Ví dụ sử dụng
visible_watermark_output = apply_visual_watermark_text(
"input.jpg",
"output_visual_copyright.jpg",
"DanQing AI: Tạo tác phẩm nghệ thuật | Bản quyền được bảo hộ"
)
# print(f"Ảnh với bản quyền hiển thị đã lưu tại: {visible_watermark_output}")
Xử lý hàng loạt và quy trình tự động hóa
Thực hiện xử lý ảnh hàng loạt
Đối với các tình huống cần xử lý một lượng lớn hình ảnh, DanQing AI cung cấp giải pháp xử lý hàng loạt hiệu quả:
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def _handle_single_file_task(input_path: str, output_path: str, processing_func: callable, **kwargs):
"""Xử lý một tệp hình ảnh đơn lẻ bằng hàm được cung cấp."""
try:
return processing_func(input_path, output_path, **kwargs)
except Exception as e:
logging.error(f"Lỗi khi xử lý tệp '{input_path}': {e}")
return {"status": "error", "file": input_path, "error": str(e)}
def process_image_directory_concurrently(input_directory: str, output_directory: str,
processing_function: callable, num_parallel_tasks: int = 4, **func_kwargs) -> list:
"""
Xử lý hàng loạt các tệp hình ảnh trong một thư mục bằng cách sử dụng đa luồng.
:param input_directory: Đường dẫn đến thư mục chứa ảnh đầu vào.
:param output_directory: Đường dẫn đến thư mục lưu ảnh đã xử lý.
:param processing_function: Hàm sẽ được áp dụng cho mỗi ảnh (nhận input_path, output_path, và kwargs).
:param num_parallel_tasks: Số lượng luồng xử lý đồng thời.
:param func_kwargs: Các đối số bổ sung để truyền tới processing_function.
:return: Danh sách các kết quả xử lý.
"""
if not os.path.exists(output_directory):
os.makedirs(output_directory)
image_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.gif')
image_files = [f for f in os.listdir(input_directory)
if f.lower().endswith(image_extensions) and os.path.isfile(os.path.join(input_directory, f))]
operation_results = []
with ThreadPoolExecutor(max_workers=num_parallel_tasks) as executor:
future_to_filepath = {}
for filename in image_files:
input_file = os.path.join(input_directory, filename)
output_file = os.path.join(output_directory, filename)
future = executor.submit(_handle_single_file_task, input_file, output_file, processing_function, **func_kwargs)
future_to_filepath[future] = filename
for future in as_completed(future_to_filepath):
original_filename = future_to_filepath[future]
try:
result = future.result()
operation_results.append(result)
logging.info(f"Xử lý thành công tệp '{original_filename}'.")
except Exception as e:
logging.error(f"Lỗi khi lấy kết quả cho tệp '{original_filename}': {e}")
operation_results.append({"status": "error", "file": original_filename, "error": str(e)})
return operation_results
# Hàm bao bọc cho tác vụ nhúng hình mờ vô hình (sử dụng hàm từ 3.1)
def invisible_watermark_processor(input_file_path: str, output_file_path: str, watermark_content: str):
"""Một hàm xử lý ảnh đơn lẻ để nhúng hình mờ vô hình."""
return embed_invisible_copyright_mark(input_file_path, output_file_path, watermark_content)
# Ví dụ sử dụng: Xử lý hàng loạt để nhúng hình mờ vô hình
# Đảm bảo các hàm embed_invisible_copyright_mark và apply_visual_watermark_text đã được định nghĩa.
# Tạo thư mục mẫu nếu chưa có
os.makedirs("./input_images", exist_ok=True)
os.makedirs("./output_images", exist_ok=True)
# Để kiểm tra, bạn có thể tạo một ảnh dummy:
# from PIL import Image
# Image.new('RGB', (100, 100), color = 'red').save('./input_images/test_image.jpg')
logging.info("Bắt đầu xử lý ảnh hàng loạt...")
batch_results = process_image_directory_concurrently(
"./input_images",
"./output_images",
invisible_watermark_processor,
num_parallel_tasks=3,
watermark_content="Tạo bởi DanQing AI"
)
logging.info("Hoàn thành xử lý hàng loạt.")
# print(batch_results)
Quy trình bảo vệ bản quyền tự động hóa
Kết hợp khả năng nhận diện API và nhúng hình mờ, bạn có thể xây dựng một quy trình xử lý hình ảnh tự động hoàn chỉnh:
import os
# Đảm bảo các hàm và lớp từ các phần trước đã được định nghĩa hoặc import.
# Ví dụ: DanQingAPIHandler, call_image_analysis_api, embed_invisible_copyright_mark, apply_visual_watermark_text
class CreativeAssetAutomation:
"""
Tự động hóa quy trình xử lý tài sản hình ảnh: nhận dạng AI, nhúng hình mờ vô hình và thêm bản quyền hiển thị.
"""
def __init__(self, api_key: str):
self.api_key = api_key
self.api_manager = DanQingAPIHandler(api_key)
def orchestrate_image_protection_flow(self, input_image_filepath: str, final_output_filepath: str) -> dict:
"""
Thực hiện chuỗi các bước tự động để xử lý và bảo vệ ảnh.
1. Gọi API để lấy mô tả nghệ thuật từ AI.
2. Nhúng hình mờ số vô hình.
3. Thêm thông tin bản quyền hiển thị rõ ràng.
4. Trả về kết quả xử lý.
"""
try:
# Bước 1: Gọi API để lấy mô tả nghệ thuật
api_description_result = self.api_manager.execute_with_rate_limit_and_retry(
input_image_filepath,
call_image_analysis_api
)
if api_description_result.get("error"):
raise Exception(f"Lỗi API: {api_description_result['error']}")
ai_generated_description = api_description_result.get("description", "Không có mô tả AI.")
logging.info(f"Đã lấy mô tả AI cho '{input_image_filepath}': {ai_generated_description[:70]}...")
# Bước 2: Nhúng hình mờ số vô hình
temp_invisible_watermark_path = final_output_filepath.replace(".jpg", "_inv.jpg").replace(".png", "_inv.png")
embed_invisible_copyright_mark(
input_image_filepath,
temp_invisible_watermark_path,
f"AI Desc: {ai_generated_description[:100]} | DanQingAI"
)
logging.info(f"Đã nhúng hình mờ vô hình vào '{temp_invisible_watermark_path}'.")
# Bước 3: Thêm bản quyền hiển thị rõ ràng
visual_copyright_text = f"Tác phẩm AI bởi DanQing\n(Mô tả: {ai_generated_description[:50]}...)"
apply_visual_watermark_text(
temp_invisible_watermark_path,
final_output_filepath,
visual_copyright_text
)
logging.info(f"Đã thêm thông tin bản quyền hiển thị vào '{final_output_filepath}'.")
# Dọn dẹp tệp tạm
os.remove(temp_invisible_watermark_path)
return {
"processing_status": "success",
"final_output_path": final_output_filepath,
"ai_description_obtained": ai_generated_description
}
except Exception as e:
logging.error(f"Quy trình tự động hóa thất bại cho '{input_image_filepath}': {e}")
return {
"processing_status": "error",
"original_file": input_image_filepath,
"error_details": str(e)
}
# Ví dụ sử dụng quy trình tự động hóa
automation_pipeline = CreativeAssetAutomation("YOUR_API_KEY_HERE")
input_sample_image = "input.jpg"
output_processed_image = "output_fully_processed.jpg"
# Tạo một ảnh dummy để test nếu không có ảnh thực
# from PIL import Image
# Image.new('RGB', (200, 200), color = 'blue').save(input_sample_image)
logging.info(f"Bắt đầu quy trình tự động hóa cho '{input_sample_image}'...")
pipeline_result = automation_pipeline.orchestrate_image_protection_flow(input_sample_image, output_processed_image)
logging.info(f"Kết quả quy trình tự động hóa: {pipeline_result}")
Trường hợp thực tế và các phương pháp hay nhất
Tự động hóa xử lý hình ảnh trên nền tảng thương mại điện tử
Một nền tảng thương mại điện tử có thể sử dụng DanQing AI để tự động tạo mô tả nghệ thuật và bảo vệ bản quyền cho hình ảnh sản phẩm:
import os
# Đảm bảo các hàm và lớp từ các phần trước đã được định nghĩa hoặc import.
class ProductImageAutomationService:
"""
Dịch vụ tự động hóa xử lý hình ảnh sản phẩm cho nền tảng thương mại điện tử,
kết hợp mô tả AI và bảo vệ bản quyền.
"""
def __init__(self, api_key: str, product_metadata: dict):
self.api_key = api_key
self.product_metadata = product_metadata
self.danqing_api_connector = DanQingAPIHandler(api_key)
def process_all_product_images_in_folder(self, image_source_dir: str, processed_output_dir: str) -> list:
"""
Xử lý tất cả hình ảnh sản phẩm trong một thư mục cụ thể.
:param image_source_dir: Thư mục chứa các ảnh sản phẩm gốc.
:param processed_output_dir: Thư mục lưu các ảnh đã xử lý.
:return: Danh sách các kết quả xử lý cho từng ảnh.
"""
if not os.path.exists(processed_output_dir):
os.makedirs(processed_output_dir)
processing_reports = []
for image_filename in os.listdir(image_source_dir):
if image_filename.lower().endswith(('.jpg', '.jpeg', '.png')):
input_filepath = os.path.join(image_source_dir, image_filename)
output_filepath = os.path.join(processed_output_dir, image_filename)
report = self._handle_single_product_image(input_filepath, output_filepath)
processing_reports.append(report)
return processing_reports
def _handle_single_product_image(self, input_path: str, output_path: str) -> dict:
"""
Xử lý một ảnh sản phẩm đơn lẻ: lấy mô tả AI, thêm hình mờ và bản quyền.
"""
try:
# Lấy mô tả AI
ai_analysis = self.danqing_api_connector.execute_with_rate_limit_and_retry(
input_path,
call_image_analysis_api
)
if ai_analysis.get("error"):
raise Exception(f"Lỗi phân tích AI: {ai_analysis['error']}")
description_from_ai = ai_analysis.get("description", "Mô tả tự động.")
# Kết hợp thông tin sản phẩm với mô tả AI
contextual_description = (
f"{self.product_metadata.get('product_name', 'Sản phẩm')} | "
f"{description_from_ai}"
)
# Thêm hình mờ số vô hình
temp_path_for_invisible = output_path.replace(".jpg", "_temp.jpg").replace(".png", "_temp.png")
embed_invisible_copyright_mark(
input_path,
temp_path_for_invisible,
f"ID SP: {self.product_metadata.get('sku_id', 'N/A')} | AI by DanQing"
)
# Thêm thông tin bản quyền hiển thị
visual_copyright_info = (
f"{self.product_metadata.get('brand_name', 'Thương hiệu')} | "
f"Được tạo bởi DanQing AI"
)
apply_visual_watermark_text(
temp_path_for_invisible,
output_path,
visual_copyright_info
)
os.remove(temp_path_for_invisible)
return {
"original_file": input_path,
"processed_file": output_path,
"generated_description": contextual_description,
"status": "success"
}
except Exception as e:
logging.error(f"Thất bại khi xử lý ảnh '{input_path}': {e}")
return {
"original_file": input_path,
"processed_file": None,
"status": "error",
"error_message": str(e)
}
# Ví dụ sử dụng
product_details = {
"sku_id": "SP98765",
"product_name": "Bộ ấm trà gốm sứ thủ công",
"brand_name": "Gốm Bát Tràng Việt"
}
ecomm_processor = ProductImageAutomationService("YOUR_API_KEY_HERE", product_details)
# Tạo thư mục mẫu nếu chưa có
os.makedirs("./product_images", exist_ok=True)
os.makedirs("./processed_ecomm_images", exist_ok=True)
# Để kiểm tra, bạn có thể tạo một ảnh dummy:
# from PIL import Image
# Image.new('RGB', (300, 300), color = 'green').save('./product_images/tea_set.jpg')
logging.info("Bắt đầu xử lý ảnh sản phẩm...")
product_results = ecomm_processor.process_all_product_images_in_folder(
"./product_images",
"./processed_ecomm_images"
)
logging.info("Hoàn thành xử lý ảnh sản phẩm.")
# print(product_results)
Giải pháp tích hợp cho nền tảng sáng tạo nội dung
Một nền tảng nội dung có thể tích hợp API DanQing AI để tự động thêm mô tả nghệ thuật và bảo vệ bản quyền cho hình ảnh được người dùng tải lên:
// Mã ví dụ tích hợp cho phía frontend (JavaScript)
class ImageProcessingClient {
constructor(clientKey) {
this.clientKey = clientKey;
this.processingServiceUrl = 'https://api.danqing.com/v1/process-image';
}
/**
* Tải lên và yêu cầu hệ thống DanQing AI xử lý hình ảnh.
* @param {File} imageFile - Tệp hình ảnh được chọn bởi người dùng.
* @returns {Promise<Object>} Đối tượng chứa URL ảnh đã xử lý, mô tả AI và siêu dữ liệu.
* @throws {Error} Nếu quá trình tải lên hoặc xử lý thất bại.
*/
async submitImageForAIProcessing(imageFile) {
const processingFormData = new FormData();
processingFormData.append('imageData', imageFile);
processingFormData.append('authenticationKey', this.clientKey);
processingFormData.append('enableInvisibleWatermark', 'true');
processingFormData.append('addVisualCopyrightText', 'true');
processingFormData.append('desiredStyle', 'artistic'); // Tham số mới
try {
const apiResponse = await fetch(this.processingServiceUrl, {
method: 'POST',
body: processingFormData,
});
if (!apiResponse.ok) {
const errorData = await apiResponse.json().catch(() => ({ message: apiResponse.statusText }));
throw new Error(`Lỗi dịch vụ: ${apiResponse.status} - ${errorData.message || JSON.stringify(errorData)}`);
}
const processingResult = await apiResponse.json();
if (processingResult.status === 'success') {
return {
finalImageUrl: processingResult.output_url,
aiDescriptionContent: processingResult.ai_generated_description,
extendedMetadata: processingResult.processing_metadata
};
} else {
throw new Error(processingResult.message || 'Xử lý hình ảnh thất bại.');
}
} catch (error) {
console.error('Lỗi khi tải lên và xử lý hình ảnh:', error);
throw error;
}
}
}
// Ví dụ sử dụng cho giao diện người dùng (thường trong một tệp script hoặc khối script HTML)
const aiProcessorClient = new ImageProcessingClient('YOUR_FRONTEND_API_KEY');
const fileUploadElement = document.getElementById('image-upload-input');
if (fileUploadElement) {
fileUploadElement.addEventListener('change', async (event) => {
const selectedFile = event.target.files[0];
if (selectedFile) {
document.getElementById('processing-status').innerText = 'Đang xử lý...';
try {
const outcome = await aiProcessorClient.submitImageForAIProcessing(selectedFile);
console.log('Kết quả xử lý:', outcome);
const imgDisplay = document.getElementById('processed-image-display');
if (imgDisplay) imgDisplay.src = outcome.finalImageUrl;
const descOutput = document.getElementById('ai-description-output');
if (descOutput) descOutput.innerText = outcome.aiDescriptionContent;
const statusOutput = document.getElementById('processing-status');
if (statusOutput) statusOutput.innerText = 'Hoàn thành!';
} catch (error) {
alert('Có lỗi xảy ra trong quá trình xử lý ảnh. Vui lòng thử lại.');
const statusOutput = document.getElementById('processing-status');
if (statusOutput) statusOutput.innerText = 'Thất bại.';
}
}
});
} else {
console.warn("Element with ID 'image-upload-input' not found. Frontend example might not work.");
}
// Để ví dụ này hoạt động, bạn cần có các phần tử HTML sau trong trang của mình:
// <input type="file" id="image-upload-input" accept="image/*">
// <img id="processed-image-display" alt="Ảnh đã xử lý" style="max-width: 100%; margin-top: 10px;">
// <p id="ai-description-output"></p>
// <p id="processing-status"></p>
Tóm tắt và Khuyến nghị
Thông qua hướng dẫn thực tế này, bạn đã làm quen với các phương pháp chính để sử dụng hệ thống DanQing AI. Dưới đây là tóm tắt các điểm quan trọng và một số khuyến nghị:
Các điểm thực hành cốt lõi
- Tối ưu hóa gọi API: Thiết lập các chính sách giới hạn tốc độ hợp lý và triển khai thuật toán lùi mũ để xử lý lỗi giới hạn lưu lượng.
- Lựa chọn kỹ thuật hình mờ: Chọn giữa hình mờ số vô hình hoặc hình mờ hiển thị mang tính nghệ thuật tùy theo yêu cầu cụ thể.
- Hiệu quả xử lý hàng loạt: Tăng cường hiệu suất xử lý ảnh số lượng lớn bằng cách sử dụng đa luồng (multi-threading) hoặc xử lý song song.
- Tùy chỉnh thông tin bản quyền: Tạo nội dung bản quyền được cá nhân hóa, phù hợp với từng kịch bản kinh doanh và mục đích sử dụng.
Đề xuất tối ưu hóa hiệu suất
- Chiến lược bộ nhớ đệm (Caching): Sử dụng bộ nhớ đệm cho các hình ảnh đã xử lý để tránh lặp lại công việc không cần thiết.
- Xử lý bất đồng bộ (Asynchronous Processing): Áp dụng các mô hình xử lý bất đồng bộ, đặc biệt với các tệp lớn, nhằm cải thiện tốc độ phản hồi của hệ thống.
- Tăng tốc phân phối với CDN: Phân phối hình ảnh sau xử lý qua Mạng phân phối nội dung (CDN) để tối ưu hóa tốc độ truy cập cho người dùng cuối.
- Giám sát và cảnh báo: Thiết lập hệ thống giám sát hoạt động API và cơ chế cảnh báo tự động cho các sự cố hoặc bất thường.
Thích ứng với các kịch bản kinh doanh
Mỗi kịch bản kinh doanh đòi hỏi một chiến lược cấu hình riêng:
- Nền tảng thương mại điện tử: Tập trung vào việc tích hợp thông tin sản phẩm với mô tả được tạo bởi AI.
- Nền tảng sáng tạo nội dung: Ưu tiên tính thẩm mỹ nghệ thuật trong trình bày và bảo vệ bản quyền.
- Nghệ thuật số: Nhấn mạnh vẻ đẹp thị giác và khả năng truyền tải giá trị văn hóa.
- Ứng dụng doanh nghiệp: Yêu cầu nhúng các yếu tố thương hiệu tùy chỉnh và phù hợp.
Hệ thống DanQing AI cung cấp các API linh hoạt và nhiều tùy chọn cấu hình phong phú, cho phép tùy chỉnh sâu rộng theo nhu cầu kinh doanh cụ thể. Nên bắt đầu từ các chức năng cơ bản, sau đó từng bước khám phá các ứng dụng nâng cao hơn.