<commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json, sys, os
import requests 
from pprint import pprint
from utils import load_obj_bin, save_obj_bin

# And pass locale in constructor
SERVER_URL = 'https://www.khanacademy.org'
TP_URL = 'https://www.khanacademy.org/translations/edit/cs/'
DEFAULT_API_RESOURCE = '/api/v1/'
# Version 2 is not documented, here used only for topic tree
# But apparently does not even fetch the whole tree, so new code will be needed
#DEFAULT_API_RESOURCE = '/api/v2/'
API2 = '/api/v2/'

kapi_headers = {
   'Content-Type': 'application/json',
   'format': 'json'
}

_EXIT_ON_HTTP_ERROR = False


class KhanAPI:

    def __init__(self, locale):
        if locale == 'en':
            self.server_url = 'https://www.khanacademy.org'
        else:
            self.server_url = 'https://' + locale + '.khanacademy.org'
        self.session = requests.Session()
        self.headers = {
            'Content-Type': 'application/json',
            'format': 'json'
        }

    def _get_url(self, url, body = {}):
        try:
            r = self.session.get(url, params = body, headers = self.headers)
            r.raise_for_status()
            return r.json()

        except requests.HTTPError as e:
            eprint('HTTP error for URL: ', url)
            eprint(e)
            try:
                eprint(r.json())
            except:
                # Catch exception when r.json is empty
                pass
            if _EXIT_ON_HTTPERROR:
                sys.exit(1)
            else:
                return {}

    def download_video(self, YTID):
        # Searching by YTID is deprecated but seems to work,
        # even searching by translated_youtube_id
        # Instead_ we should be calling this by readable_id
        url = SERVER_URL + DEFAULT_API_RESOURCE + 'videos/'  + YTID
        json_response = self._get_url(url)
        return json_response


    # TODO: Convert to V2 API
    # It seems that the kind argument does not work?
    # EDIT: It seems that the V2 approach will not work here...
    def download_topic_tree(self, content_type):
        """Content type can be 'video', 'exercise', 'article'"""
 
        #url = SERVER_URL + API2 + 'topics/topictree'
        url = SERVER_URL + DEFAULT_API_RESOURCE + 'topictree'
        body = {
            "kind": content_type
        }
        json_response = self._get_url(url, body)
        return json_response


# We want this to be decoupled from KhanAPI object to allow for off-line use
class KhanContentTree():

    def __init__(self, locale, content_type):
        self.content_tree = None
        self.content_type = content_type
        self.file_name = "khan_tree_" + locale + '_' + self.content_type + "_bin.pkl"

    def save(self, tree):
        save_obj_bin(tree, self.file_name)
        self.content_tree = tree

    def load(self):
        if not os.path.isfile(self.file_name):
            print("ERROR: Could not load content tree from file '%s'" % (self.file_name))
            # TODO: Try to download Khan Tree here
            sys.exit(1)
        self.content_tree = load_obj_bin(self.file_name)

    def get(self):
        if self.content_tree is None:
            self.load()
        return self.content_tree<commit_msg>MAJOR FIX: Downloading KA tree for correct locale<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json, sys, os
import requests 
from pprint import pprint
from utils import load_obj_bin, save_obj_bin

# And pass locale in constructor
SERVER_URL = 'https://www.khanacademy.org'
TP_URL = 'https://www.khanacademy.org/translations/edit/cs/'
DEFAULT_API_RESOURCE = '/api/v1/'
# Version 2 is not documented, here used only for topic tree
# But apparently does not even fetch the whole tree, so new code will be needed
#DEFAULT_API_RESOURCE = '/api/v2/'
API2 = '/api/v2/'

kapi_headers = {
   'Content-Type': 'application/json',
   'format': 'json'
}

_EXIT_ON_HTTP_ERROR = False


class KhanAPI:

    def __init__(self, locale):
        if locale == 'en':
            self.server_url = 'https://www.khanacademy.org'
        else:
            self.server_url = 'https://' + locale + '.khanacademy.org'
        self.default_api_resource = '/api/v1/'
        self.session = requests.Session()
        self.headers = {
            'Content-Type': 'application/json',
            'format': 'json'
        }

    def _get_url(self, url, body = {}):
        try:
            r = self.session.get(url, params = body, headers = self.headers)
            r.raise_for_status()
            return r.json()

        except requests.HTTPError as e:
            eprint('HTTP error for URL: ', url)
            eprint(e)
            try:
                eprint(r.json())
            except:
                # Catch exception when r.json is empty
                pass
            if _EXIT_ON_HTTPERROR:
                sys.exit(1)
            else:
                return {}

    def download_video(self, YTID):
        # Searching by YTID is deprecated but seems to work,
        # even searching by translated_youtube_id
        # Instead_ we should be calling this by readable_id
        url = self.server_url + self.default_api_resource + 'videos/'  + YTID
        json_response = self._get_url(url)
        return json_response


    # TODO: Convert to V2 API
    # It seems that the kind argument does not work?
    # EDIT: It seems that the V2 approach will not work here...
    def download_topic_tree(self, content_type):
        """Content type can be 'video', 'exercise', 'article'"""
 
        #url = self.server_url + API2 + 'topics/topictree'
        url = self.server_url + self.default_api_resource + 'topictree'
        body = {
            "kind": content_type
        }
        json_response = self._get_url(url, body)
        return json_response


# We want this to be decoupled from KhanAPI object to allow for off-line use
class KhanContentTree():

    def __init__(self, locale, content_type):
        self.content_tree = None
        self.content_type = content_type
        self.file_name = "khan_tree_" + locale + '_' + self.content_type + "_bin.pkl"

    def save(self, tree):
        save_obj_bin(tree, self.file_name)
        self.content_tree = tree

    def load(self):
        if not os.path.isfile(self.file_name):
            print("ERROR: Could not load content tree from file '%s'" % (self.file_name))
            # TODO: Try to download Khan Tree here
            sys.exit(1)
        self.content_tree = load_obj_bin(self.file_name)

    def get(self):
        if self.content_tree is None:
            self.load()
        return self.content_tree
{'fraction_non_alphanumeric': 0.10231370192307693, 'fraction_numerical': 0.0037560096153846155, 'mean_word_length': 2.200480769230769, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 8, 'lorem ipsum': 0, 'www.': 6, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 7, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5635094', 'n_tokens_mistral': 2050, 'n_tokens_neox': 2011, 'n_words': 572}