电商图片翻译 智能抠图 智能元素识别 水印 抠图 消除 商品标题描述生成
评论
收藏

电商图片翻译 智能抠图 智能元素识别 水印 抠图 消除 商品标题描述生成

经验分享
蕾恩恩
2025-12-18 10:51·浏览量:479
蕾恩恩
影刀专家
影刀认证工程师
发布于 2025-12-17 17:41更新于 2025-12-18 10:51479浏览

这是一个1688旗下的智能体遨虾,目前是免费的,api的话收费不太贵,代码目前用api实现了图片翻译Pro版  效果还是蛮不错的   会自动排版,可以看下图效果   还可以利用只能元素识别之后再进行后面的操作 上限比较高   唯一觉得不太好的地方就是如果是本地图片需要转换成链接之后才能准换

api文档和注册地址: https://www.alphashop.cn

# 使用提醒:
# 1. xbot包提供软件自动化、数据表格、Excel、日志、AI等功能
# 2. package包提供访问当前应用数据的功能,如获取元素、访问全局变量、获取资源文件等功能
# 3. 当此模块作为流程独立运行时执行main函数
# 4. 可视化流程中可以通过"调用模块"的指令使用此模块

import xbot
from xbot import print, sleep
from .import package
from .package import variables as glv

def main(args):
    pass
import requests
import json
from datetime import datetime, timedelta
import time
import jwt

def sign(ak: str, sk: str) -> str:

    try:
        # 过期时间:当前时间 + 1800秒(30分钟)
        expired_at = datetime.utcnow() + timedelta(seconds=1800)
        
        # 生效时间:当前时间 - 5秒
        not_before = datetime.utcnow() - timedelta(seconds=5)
        
        # JWT header
        headers = {
            "alg": "HS256",
            "typ": "JWT"
        }
        
        # JWT payload
        payload = {
            "iss": ak,  # 签发者 (issuer)
            "exp": expired_at,  # 过期时间 (expiration time)
            "nbf": not_before,  # 生效时间 (not before)
            "iat": datetime.utcnow()  # 签发时间 (issued at) - 可选,但通常包含
        }
        
        # 生成token
        token = jwt.encode(
            payload=payload,
            key=sk,
            algorithm="HS256",
            headers=headers
        )
        
        # PyJWT返回的是字符串,直接返回
        return token
        
    except Exception as e:
        print(f"生成JWT token时出错: {e}")
        return None



def translate_image(image_url: str, source_lang: str, target_lang: str, 
                   including_product_area=None, use_image_editor=None, translating_brand=None):
    """
    Args:
        ak: Access Key
        sk: Secret Key
        image_url: 原图URL
        source_language: 图片内容语种
        target_language: 目标语种
        including_product_area: 是否翻译商品主体上文字
        use_image_editor: 是否使用图翻编辑器协议
        translating_brand: 是否翻译品牌上文字
    """
    
    # 1. 生成鉴权token
    ak = ""  # 填写Access Key
    sk = ""  # 填写Secret Key
    auth_token = sign(ak, sk)
    if not auth_token:
        print("生成鉴权token失败")
        return None
    
    # 2. 准备请求URL
    base_url = "https://api.alphashop.cn/ai.image.translateImagePro/1.0"
    
    # 3. 准备请求头
    headers = {
        "Content-Type": "application/json",
        # "Authorization": f"Bearer {auth_token}"
        "Authorization": f"Bearer {auth_token}"
    }
    
    # 4. 准备请求体
    request_body = {
        "imageUrl": image_url,
        "sourceLanguage": source_lang,
        "targetLanguage": target_lang
    }
    
    # 添加可选参数(如果提供了的话)
    if including_product_area is not None:
        request_body["includingProductArea"] = including_product_area
    
    if use_image_editor is not None:
        request_body["useImageEditor"] = use_image_editor
    
    if translating_brand is not None:
        request_body["translatingBrandInTheProduct"] = translating_brand
    
    try:
        # 5. 发送POST请求
        response = requests.post(
            url=base_url,
            headers=headers,
            json=request_body,  # 使用json参数会自动序列化并设置Content-Type
            timeout=30  # 设置超时时间
        )
        
        # 6. 处理响应

        if response.status_code == 200:
            try:
                # 解析响应
                result = response.json()
                print(result)
                # 按照你提供的实际响应格式处理
                if "result" in result:
                    api_result = result.get("result", {})
                    # 输出完整的响应结构

                    
                    if api_result.get("success"):
                        print(f"返回消息: {api_result.get('retMsg')}")
                        
                        # 提取翻译结果
                        translate_result = api_result.get("result", {})
                        if translate_result:
                            print(f"翻译后图片URL: {translate_result.get('translatedImageUrl')}")
                            return translate_result.get('translatedImageUrl')
                            # 解析editInfo字段
                            edit_info_str = translate_result.get('editInfo')
                            if edit_info_str:
                                try:
                                    edit_info = json.loads(edit_info_str)
                                    print(f"修复后图片URL: {edit_info.get('repairedUrl')}")
                                    print(f"使用的字体: {edit_info.get('font')}")
                                    
                                    # 提取所有翻译的文本区域
                                    text_areas = edit_info.get('textAreas', [])
                                    if text_areas:
                                        print(f"\n翻译的文本区域 ({len(text_areas)} 个):")
                                        for i, area in enumerate(text_areas, 1):
                                            print(f"  区域 {i}:")
                                            print(f"    - 原文: {area.get('content')}")
                                            print(f"    - 原文大小: {area.get('fontsize')}px")
                                            
                                            # 提取翻译后的文本
                                            texts = area.get('texts', [])
                                            if texts:
                                                for text in texts:
                                                    if text.get('valid'):
                                                        print(f"    - 译文: {text.get('value')}")
                                                        print(f"    - 译文语言: {text.get('language')}")
                                                        print(f"    - 译文大小: {text.get('fontsize')}px")
                                        
                                    # 如果有商品区域信息
                                    goods_rects = edit_info.get('goodsRects', {})
                                    if goods_rects:
                                        print(f"\n商品区域位置: {goods_rects}")
                                        
                                except json.JSONDecodeError as e:
                                    print(f"解析editInfo失败: {e}")
                        
                        return result
                    else:
                        print(f"API调用失败: {api_result.get('retMsg')}")
                        return result
                else:
                    print(f"响应格式异常: {result}")
                    return result
                    
            except Exception as e:
                print(f"解析响应失败: {e}")
                print(f"原始响应: {response.text}")
                return {"error": "解析响应失败", "raw_response": response.text}
        print(f"响应头: {dict(response.headers)}")
        

    except Exception as e:
        print(f"请求过程中发生错误: {e}")
        return None




# 必填参数
image_url = ""  # 替换为你的图片URL

source_language = "zh"  # 源语言,如:zh(中文)、en(英文)、ja(日文)等
target_language = "ko"  # 目标语言

# 可选参数
including_product_area = False  # 是否翻译商品主体上文字
use_image_editor = False  # 是否使用图翻编辑器协议
translating_brand = False  # 是否翻译品牌上文字

# 调用API
result = translate_image(
    image_url=image_url,
    source_lang=source_language,
    target_lang=target_language,
    including_product_area=including_product_area,
    use_image_editor=use_image_editor,
    translating_brand=translating_brand
)



收藏10
全部评论1
最新
发布评论
评论