Ir ao contido

Ordenar

Este servizo de PhotoILike proporciona unha ordenación automática por estancias. Este servizo de ordenación está pensado para utilizar como entrada os resultados dos servizos PhotoScore e PhotoTag, aínda que isto non é estritamente necesario.

Petición

POST https://api.photoilike.com/v2.0/sort

Cabeceiras

Campos

Clave Valor
Authorization string
Requirido
Token de sesión precedido pola palabra Bearer.

Corpo da solicitude

O corpo da solicitude contén datos coa seguinte estrutura:

Representación JSON

{
    "client-key": string,
    "data": [
        {
            "identifier": string,
            "label": string,
            "score": float
        },
        ...
    ],
    "preferences": [
        {
            "position": int,
            "label": string
        }
    ]
    "top": {
        "amount": int,
        "blacklist": [string, ...]
    },
}

Campos

Parámetro Información
client-key string
Requirido
Client-key do usuario final que solicita a ordenación de imaxes.
data array
Requirido
Array que contén as imaxes para ordenar.
data[item].identifier string
Requerido
Calquera tipo de identificador da imaxe (que non supere os 2000 caracteres). Pode ser unha URL, un identificador de base de datos, etc.
data[item].label string
Requirido
Etiqueta que identifica a estancia (non ha de superar os 100 caracteres).
data[item].score string
Requirido
Puntuación que indica o atractivo da imaxe.
preferences array
Opcional
Array que contén a preferencia de orde baseada en etiquetas.
preferences[item].position string
Requirido
Orde da etiqueta (empeza no un e incrementa iterativamente).
preferences[item].label string
Requirido
Etiqueta (non ha de superar os 100 caracteres).
top object
Opcional
Permite indicar as imaxes que se mostrarán nas primeiras posicións. Neste top mostrarase a mellor imaxe de cada etiqueta.
top.amount object
Requirido
Número de etiquetas que mostrarán a súa mellor imaxe nas primeiras posicións.
O valor por defecto que se usará, se non se indica ningún valor, é 3.
top.blacklist array
Opcional
As imaxes que conteñan unha etiqueta desta lista non aparecerán no top (as etiquetas non han de superar os 100 caracteres).

Resposta da solicitude

En caso de éxito, o código de estado HTTP no encabezado da resposta é 200 OK e o corpo da resposta contén un array cos elementos ordenados.

Representación JSON

[
    {
        "position": int,
        "identifier": string,
        "label": string,
        "score": float
    },
    ...
]

Campos

Parámetro Información
position int
Posición da imaxe dentro do conxunto.
identifier string
Identificador da imaxe que se pasou á solicitude.
label string
Etiqueta da imaxe que se pasou na solicitude.
score string
Puntuación da imaxe que se pasou na solicitude.

Exemplo de petición

DATA='[{"identifier": "https://example.org/img12.jpg", "label": "label1", "score": 8.5}, {"identifier": "https://example.org/img11.jpg", "label": "label1", "score": 9.5}, {"identifier": "https://example.org/img31.jpg", "label": "label3", "score": 9.25}, {"identifier": "https://example.org/img22.jpg", "label": "label2", "score": 7.5}, {"identifier": "https://example.org/img21.jpg", "label": "label2", "score": 5.25}]'

PREFERENCES='[{"position": 1, "label": "label1"}, {"position": 2, "label": "label2"}, {"position": 3, "label": "labelX"}]'

curl --request POST \
--header "Content-Type: application/json" \
--header "Authorization: Bearer {YOUR.SESSION.TOKEN}" \
--data '{"client-key": "{ACTIVE_CLIENT_KEY}", "data": '"$DATA"', "preferences": '"$PREFERENCES"'}' \
https://api.photoilike.com/v2.0/sort
import requests

header = {
    # Add your token session (1)
    'Authorization': 'Bearer YOUR.SESSION.TOKEN'
}

# Add your images with their labels and scores (2)
elements = [
    {
        'identifier': 'https://example.org/img12.jpg',
        'label': 'label1', 'score': 8.5
    }, {
        'identifier': 'https://example.org/img11.jpg',
        'label': 'label1', 'score': 9.5
    }, {
        'identifier': 'https://example.org/img31.jpg',
        'label': 'label3', 'score': 9.25
    }, {
        'identifier': 'https://example.org/img22.jpg',
        'label': 'label2', 'score': 7.5
    },
    {
        'identifier': 'https://example.org/img21.jpg',
        'label': 'label2', 'score': 5.25
    }
]

payload = {
    # Add an active client key (3)
    'client-key': 'ACTIVE_CLIENT_KEY',
    'data': elements
}

# If you want that some labels appears on the top use the preferences (4)
payload['preferences'] = [
    {'position': 1, 'label': 'label1'},
    {'position': 2, 'label': 'label2'},
    {'position': 3, 'label': 'labelX'}
]

endpoint = 'https://api.photoilike.com/v2.0/sort'

# Make the request
r = requests.post(endpoint, headers=header, json=payload)

# Response in json format
response = r.json()
  1. Asegúrese de substituír YOUR.SESSION.TOKEN por un token de sesión válido
  2. Anada unha listaxe das imaxes coas súas puntuacións e etiquetas. O valor de identifier pode ser calquera identificador (URL, identificador da base de datos, etc)
  3. Asegúrese de substituír ACTIVE_CLIENT_KEY por un client-key válido
  4. Se o desexa, pode establecer as preferencias que considere oportunas
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import org.json.JSONArray;
import org.json.JSONObject;

public class Sort {

    public static void main(String[] args) throws Exception {
        // add your session token (1)
        String bearerToken = String.format("Bearer %s", "YOUR.SESSION.TOKEN");

        // add your images with their labels and scores (2)
        JSONObject element1 = new JSONObject();
        element1.put("identifier", "https://example.org/img12.jpg");
        element1.put("label", "label1");
        element1.put("score", 8.5);
        JSONObject element2 = new JSONObject();
        element2.put("identifier", "https://example.org/img11.jpg");
        element2.put("label", "label1");
        element2.put("score", 9.5);
        JSONObject element3 = new JSONObject();
        element3.put("identifier", "https://example.org/img31.jpg");
        element3.put("label", "label3");
        element3.put("score", 9.25);
        JSONObject element4 = new JSONObject();
        element4.put("identifier", "https://example.org/img22.jpg");
        element4.put("label", "label2");
        element4.put("score", 7.5);
        JSONObject element5 = new JSONObject();
        element5.put("identifier", "https://example.org/img21.jpg");
        element5.put("label", "label2");
        element5.put("score", 5.25);

        JSONArray elements = new JSONArray();
        elements.put(element1);
        elements.put(element2);
        elements.put(element3);
        elements.put(element4);
        elements.put(element5);

        // if you want that some labels appears on the top use the preferences (4)
        JSONObject preference1 = new JSONObject();
        preference1.put("position", 1);
        preference1.put("label", "label1");
        JSONObject preference2 = new JSONObject();
        preference2.put("position", 2);
        preference2.put("label", "label2");
        JSONObject preference3 = new JSONObject();
        preference3.put("position", 3);
        preference3.put("label", "labelX");

        JSONArray preferences = new JSONArray();
        preferences.put(preference1);
        preferences.put(preference2);
        preferences.put(preference3);

        JSONObject payload = new JSONObject();
        // add an active client key (3)
        payload.put("client-key", "ACTIVE_CLIENT_KEY");
        payload.put("data", elements);
        payload.put("preferences", preferences);


        String endpoint = "https://api.photoilike.com/v2.0/sort";

        // build the request
        HttpURLConnection connection = (HttpURLConnection) new URL(endpoint).openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Authorization", bearerToken);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        OutputStream os = connection.getOutputStream();
        byte[] input = payload.toString().getBytes(StandardCharsets.UTF_8);
        os.write(input, 0, input.length);

        // make the request
        BufferedReader br = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)
        );
        StringBuilder response = new StringBuilder();

        for (String responseLine = null; (responseLine = br.readLine()) != null; response.append(responseLine.trim()))
            ;

        // Response in json format
        JSONArray json = new JSONArray(response.toString());
    }

}
  1. Asegúrese de substituír YOUR.SESSION.TOKEN por un token de sesión válido
  2. Anada unha listaxe das imaxes coas súas puntuacións e etiquetas. O valor de identifier pode ser calquera identificador (URL, identificador da base de datos, etc)
  3. Asegúrese de substituír ACTIVE_CLIENT_KEY por un client-key válido
  4. Se o desexa, pode establecer as preferencias que considere oportunas
<?php

  // Add your token session (1)
  $headers = array(
    'Content-Type:application/json',
    'Authorization: Bearer YOUR.SESSION.TOKEN'
  );

  // Add your images with their labels and scores (2)
  $elements = array(
    array(
      'identifier' => 'https://example.org/img12.jpg',
      'label' => 'label1', 'score' => 8.5
    ),
    array(
      'identifier' => 'https://example.org/img11.jpg',
      'label' => 'label1', 'score' => 9.5
    ),
    array(
      'identifier' => 'https://example.org/img31.jpg',
      'label' => 'label3', 'score' => 9.25
    ),
    array(
      'identifier' => 'https://example.org/img22.jpg',
      'label' => 'label2', 'score' => 7.5
    ),
    array(
      'identifier' => 'https://example.org/img21.jpg',
      'label' => 'label2', 'score' => 5.25
    )
  );

  // If you want that some labels appears on the top use the preferences (4)
  $preferences = array(
    array(
      'label' => 'label1', 'position' => 1
    ),
    array(
      'label' => 'label2', 'position' => 2
    ),
    array(
      'label' => 'labelX', 'position' => 3
    )
  );

  // Add an active client key (3)
  $payload = json_encode(array(
    'client-key' => 'ACTIVE_CLIENT_KEY',
    'data' => $elements,
    'preferences' => $preferences
  ));

  $endpoint = "https://api.photoilike.com/v2.0/sort";

  $ch = curl_init($endpoint);
  curl_setopt($ch,  CURLOPT_POSTFIELDS, $payload);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  // Make the request
  $result = curl_exec($ch);

  curl_close($ch);

  // Response in json format
  $response = json_decode($result);

 ?>
  1. Asegúrese de substituír YOUR.SESSION.TOKEN por un token de sesión válido
  2. Anada unha listaxe das imaxes coas súas puntuacións e etiquetas. O valor de identifier pode ser calquera identificador (URL, identificador da base de datos, etc)
  3. Asegúrese de substituír ACTIVE_CLIENT_KEY por un client-key válido
  4. Se o desexa, pode establecer as preferencias que considere oportunas