# Sample Code

The following is some sample code that provides an example of performing a basic "identify music" audio search.

{% tabs %}
{% tab title="Python" %}
{% code title="main.py" lineNumbers="true" %}

```python
#!/usr/bin/env python3

import json
import pex

CLIENT_ID = "#YOUR_CLIENT_ID_HERE"
CLIENT_SECRET = "#YOUR_CLIENT_SECRET_HERE"
INPUT_FILE = "/path/to/file.mp3"

def main():
    # Initialize and authenticate the client
    client = pex.PexSearchClient(CLIENT_ID, CLIENT_SECRET)

    # Create an audio fingerprint from input file
    ft = client.fingerprint_file(INPUT_FILE, pex.FingerprintType.AUDIO)

    # Build an identify music search request
    req = pex.PexSearchRequest(fingerprint=ft, type=pex.PexSearchType.IDENTIFY_MUSIC)

    # Perform the lookup
    result = do_lookup(client, req)

    # Print the result
    print(json.dumps(result, indent=2))
    
    
def do_lookup(client, req):
    while True:
        try:
            # Start the search
            future = client.start_search(req)

            # Return the result
            return future.get()

        except pex.Error as err:
            # Raise the error if it's not retryable
            if not err.is_retryable:
                raise err

            # Log the error
            print(err)
            print("retrying lookup...")

            # Sleep for 1s or use exponential backoff
            time.sleep(1)

            # Retry the lookup
            continue


if __name__ == '__main__':
    main()
```

{% endcode %}
{% endtab %}

{% tab title="Go" %}
{% code title="main.go" lineNumbers="true" %}

```go
package main

import (
	"encoding/json"
	"fmt"

	pex "github.com/Pexeso/pex-sdk-go/v4"
)

const (
	clientID     = "#YOUR_CLIENT_ID_HERE"
	clientSecret = "#YOUR_CLIENT_SECRET_HERE"
	inputFile    = "/path/to/file.mp3"
)

func main() {
	// Initialize and authenticate the client
	client, err := pex.NewPexSearchClient(clientID, clientSecret)
	if err != nil {
		panic(err)
	}
	defer client.Close()

	// Create an audio fingerprint from input file
	ft, err := client.FingerprintFile(inputFile, pex.FingerprintTypeAudio)
	if err != nil {
		panic(err)
	}

	// Build an identify music search request
	req := &pex.PexSearchRequest{
		Fingerprint: ft,
		Type:        pex.IdentifyMusic,
	}

	// Perform the lookup
	res, err := doLookup(client, req)
	if err != nil {
		panic(err)
	}

	// Print the result
	j, err := json.MarshalIndent(res, "", "  ")
	if err != nil {
		panic(err)
	}
	fmt.Println(string(j))
}

func doLookup(client *pex.PexSearchClient, req *pex.PexSearchRequest) (*pex.PexSearchResult, error) {
  for {
    // Start the search
    fut, err := client.StartSearch(req)
    if err != nil {
      if isFatal(err) {
        return nil, err
      }

      // Retry the lookup
      continue
    }

    // Retrieve the result
    res, err := fut.Get()
    if err != nil {
      if isFatal(err) {
        return nil, err
      }

      // Retry the lookup
      continue
    }

    return res, nil
  }
}

func isFatal(err error) bool {
  pexErr, ok := err.(*pex.Error)
  if !ok {
    return true
  }

  if !pexErr.IsRetryable {
    return true
  }

  // Log the error
  fmt.Println(err)
  fmt.Println("retrying lookup...")

  // Sleep for 1s or use exponential backoff
  time.Sleep(time.Second)

  return false
}
```

{% endcode %}
{% endtab %}

{% tab title="PHP" %}
{% code title="index.php" lineNumbers="true" %}

```php
<?php

require __DIR__ . '/vendor/autoload.php';

const CLIENT_ID = "#YOUR_CLIENT_ID_HERE";
const CLIENT_SECRET = "#YOUR_CLIENT_SECRET_HERE";
const INPUT_FILE = "/path/to/file.mp3";

function main() {
  // Initialize and authenticate the client
  $client = new Pex\PexSearchClient(CLIENT_ID, CLIENT_SECRET);

  // Create an audio fingerprint from input file
  $ft = $client->fingerprintFile(INPUT_FILE, [Pex\FingerprintType::Audio]);

  // Build an identify music search request
  $req = new Pex\PexSearchRequest($ft, $type=Pex\PexSearchType::IdentifyMusic);

  // Perform the lookup
  $res = doLookup($client, $req);

  // Print the result
  var_dump($res);
}

function doLookup($client, $req) {
  while (true) {
    try {
      // Start the search
      $fut = $client->startSearch($req);

      // Retrieve the result
      return $fut->get();
    } catch (Pex\Error $err) {
      // Rethrow the error if it's not retryable
      if (!$err->isRetryable()) {
        throw $err;
      }

      // Log the error
      echo $err, "\n";
      echo "retrying lookup...\n";

      // Sleep for 1s or use exponential backoff
      sleep(1);

      // Retry the lookup
      continue;
    }
  }
}

main();
```

{% endcode %}
{% endtab %}

{% tab title="Node.js" %}
{% code title="main.js" lineNumbers="true" %}

```javascript
const pex = require("pex-sdk");

const CLIENT_ID = "#YOUR_CLIENT_ID_HERE";
const CLIENT_SECRET = "#YOUR_CLIENT_SECRET_HERE";
const INPUT_FILE = "/path/to/file.mp3";

async function main() {
  // Initialize and authenticate the client
  let client = new pex.PexSearchClient(CLIENT_ID, CLIENT_SECRET)

  // Connect to the PexSearch server. This operation is asynchronous and
  // returns a promise, just like most operations in this package.
  await client.connect()

  // Create an audio fingerprint from input file
  let ft = await client.fingerprintFile(INPUT_FILE, [pex.AUDIO])

  // Perform an identify music search and await the result
  let result = await doLookup(client, {
    fingerprint: ft,
    type: pex.IDENTIFY_MUSIC,
  })

  // Pretty print the result
  console.log(JSON.stringify(result, null, 2))
}

async function doLookup(client, req) {
  while(true) {
    try {
      // Start the search
      let fut = client.startSearch(req)
      
      // Retrieve the result
      return await fut;
    } catch(err) {
      // Rethrow the error if it's not retryable
      if (!err.isRetryable) {
        throw err
      }

      // Log the error
      console.log(err)
      console.log("retrying lookup...")

      // Sleep for 1s or use exponential backoff
      await new Promise(r => setTimeout(r, 1000))

      // Retry the lookup
      continue
    }
  }
}

main()
```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.pex.com/search/sdk-integration/search-pex-registry/sample-code.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
