File size: 1,891 Bytes
8e786b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import logging
import os
import json
import requests

CYANITE_API_URL = "https://api.cyanite.ai/graphql"
CYANITE_ACCESS_TOKEN = os.getenv("CYANITE_ACCESS_TOKEN")

def free_text_search(search_text, num_tracks=5):
    headers = {
        "Authorization": f"Bearer {CYANITE_ACCESS_TOKEN}",
        "Content-Type": "application/json"
    }

    query = '''
    query FreeTextSearch($searchText: String!, $numTracks: Int!) {
      freeTextSearch(
        first: $numTracks
        target: { library: {} }
        searchText: $searchText
      ) {
        ... on FreeTextSearchError {
          message
          code
        }
        ... on FreeTextSearchConnection {
          edges {
            cursor
            node {
              id
              title
            }
          }
        }
      }
    }
    '''

    variables = {
        "searchText": search_text,
        "numTracks": num_tracks
    }
    import time

    start_time = time.time()

    response = requests.post(
      CYANITE_API_URL,
      headers=headers,
      json={'query': query, 'variables': variables}
    )

    end_time = time.time()
    time_taken = end_time - start_time
    logging.warning(f"Cyanite API: Time taken: {time_taken} seconds")

    if response.status_code == 200:
        songs = extract_songs_from_response(response.json())
        if songs:
            return songs
        else:
            raise Exception("No songs found")
    else:
        raise Exception(f"Query failed with status code {response.status_code}")

def extract_songs_from_response(response_json):
    try:
        edges = response_json['data']['freeTextSearch']['edges']
        if not edges:
            return None  # No songs found
        songs = [{"id": edge["node"]["id"], "title": edge["node"]["title"]} for edge in edges]
        return songs
    except KeyError:
        raise Exception("Invalid response format")