#!/bin/python3

import argparse
import requests
import json
from datetime import datetime


API_URL = 'https://zylalabs.com/api/45/image+tagging+content+api/120/tags+for+images'

argparser = argparse.ArgumentParser(description='Test AI Image Tagging | zylalabs.com')


argparser.add_argument('-cf', '--client-file', default='', help='File with Client ID and Secret')
argparser.add_argument('-ak', '--api-key', default='', help='API Key (if set, ignore --client-file)')
argparser.add_argument('-cs', '--client-secret', default='', help='Client Secret (if set, ignore --client-file)')
argparser.add_argument('-i', '--image-url', help='Image URL')
argparser.add_argument('-api', '--api-url', default=API_URL, help='API URL (default: {})'.format(API_URL))
argparser.add_argument('-t', '--threshold', default='7', help='Threshold for confidence (default, min: 7)')
argparser.add_argument('-l', '--language', default='en', help='Language (default: en)')


if __name__ == '__main__':
    args = argparser.parse_args()

    api_key = args.api_key

    if args.client_file != '':
        with open(args.client_file, 'r') as f:
            content = f.read()
            parts = content.split('\n')
            if len(parts) > 0:
                c_id = parts[0].strip()
                if len(c_id) > 0:
                    api_key = c_id

    image = args.image_url
    print('Image URL:', image)

    threshold = int(args.threshold)
    lang = args.language
    if lang == '':
        lang = 'en'

    start = datetime.now()
    response = requests.get(
        API_URL,
        params={
            'image_url': image,
            'language': lang,
            'threshold': threshold,
        },
        headers={
            'Authorization': 'Bearer ' + api_key,
        })
    took = datetime.now() - start
    print('Request took', took)

    if response.status_code != 200:
        print(response.text)
        exit(1)

    response = json.loads(response.text)
    print('Response:', json.dumps(response, indent=4))
