<gh_stars>1-10
import requests
import time
import os
import json
from avclass.labeler import AVClassLabeler

# Load API key
api_path = os.path.join(
        os.path.dirname(
            os.path.abspath(__file__)), "vtapi.txt")
apikey = open(api_path).read().strip()

def get_vt_info(sha256sum):

    response = requests.get("https://www.virustotal.com/api/v3/files/" + sha256sum, headers = {"x-apikey" : apikey});

    while True:
        if response.status_code == 200:
            # return response.json() # Return content deserialized to a dictionary
            return response.content # Return raw content bytes
        elif response.status_code == 429:
            print("Quota exeeded, waiting 15 secs")
            time.sleep(15)
        else:
            raise ApiError(response)

# Combine a folder of VT files into one compatible with AVClass2
def combine_vt_files(in_dir, out_full_path):
    with open(out_full_path, 'w') as combined_file:

        for json_filename in os.listdir(in_dir):
            with open(in_dir + json_filename, "r") as json_file:

                for line in json_file:
                    combined_file.write(line.strip())
            combined_file.write('\n')

# Run avclass2 and return the resulting label array
def run_avclass2(file):
    av_labeler = AVClassLabeler()
    av_result = av_labeler.run(
        files=file,
        data_type="vt3",
        path_export=True
    )
    return av_result["labels"]

# Get app from avclass result by sha256 value.
# We do this by looking up the file name from the json dir, which is *sha256*.json
# In the file we get the MD5 of the app, which is what AVClass2 uses in its result.
def get_app_by_sha256(sha256, json_dir, av_labels):
    json_data = json.load(open(json_dir + sha256.upper() + ".json", "r"))
    md5 = json_data["data"]["attributes"]["md5"]

    for app in av_labels:
        if md5 == app["hash"]:
            return app

    return None


# Extract the labels of a single app
def get_labels(app):
    top_tag = ""
    top_tag_count = 0
    all_tags = {}
    grayware_tag_found = False
    grayware_count = 0
    tags = app["tags"]

    for tag in tags:
        classification = tag["tag"]
        category = tag["category"]
        count = tag["count"]
        if category == "CLASS":# or category == "FAM":

            if count > top_tag_count and classification != "grayware":
                top_tag = classification
                top_tag_count = count

            if classification == "grayware":
                grayware_tag_found = True
                grayware_count = count

            all_tags[classification] = count

    if top_tag == '':
        if grayware_tag_found:
            # Only tag as grayware if it's the only tag
            top_tag = "grayware"
            top_tag_count = grayware_count
        else:
            top_tag = "no tag"

    return { "top" : top_tag, "all" : all_tags }


def get_label_stats(apps):
    all_tags = {} # All tags from all apps, grouped by name
    top_tags = {} # Tag counts based on top tag per each app (excluding grayware)

    for app in apps:
        app_tags = get_labels(app)

        if app_tags["top"] not in top_tags:
            top_tags[app_tags["top"]] = 1
        else:
            top_tags[app_tags["top"]] += 1

        for tag in app_tags["all"]:
            if tag not in all_tags:
                all_tags[tag] = 1
            else:
                all_tags[tag] += 1

    return { "top_tags" : top_tags, "all_tags" : all_tags }


class ApiError(Exception):
    pass

import requests
import time
import os
import json
from avclass.labeler import AVClassLabeler

# Load API key
api_path = os.path.join(
        os.path.dirname(
            os.path.abspath(__file__)), "vtapi.txt")
apikey = open(api_path).read().strip()

def get_vt_info(sha256sum):

    response = requests.get("https://www.virustotal.com/api/v3/files/" + sha256sum, headers = {"x-apikey" : apikey});

    while True:
        if response.status_code == 200:
            # return response.json() # Return content deserialized to a dictionary
            return response.content # Return raw content bytes
        elif response.status_code == 429:
            print("Quota exeeded, waiting 15 secs")
            time.sleep(15)
        else:
            raise ApiError(response)

# Combine a folder of VT files into one compatible with AVClass2
def combine_vt_files(in_dir, out_full_path):
    with open(out_full_path, 'w') as combined_file:

        for json_filename in os.listdir(in_dir):
            with open(in_dir + json_filename, "r") as json_file:

                for line in json_file:
                    combined_file.write(line.strip())
            combined_file.write('\n')

# Run avclass2 and return the resulting label array
def run_avclass2(file):
    av_labeler = AVClassLabeler()
    av_result = av_labeler.run(
        files=file,
        data_type="vt3",
        path_export=True
    )
    return av_result["labels"]

# Get app from avclass result by sha256 value.
# We do this by looking up the file name from the json dir, which is *sha256*.json
# In the file we get the MD5 of the app, which is what AVClass2 uses in its result.
def get_app_by_sha256(sha256, json_dir, av_labels):
    json_data = json.load(open(json_dir + sha256.upper() + ".json", "r"))
    md5 = json_data["data"]["attributes"]["md5"]

    for app in av_labels:
        if md5 == app["hash"]:
            return app

    return None


# Extract the labels of a single app
def get_labels(app):
    top_tag = ""
    top_tag_count = 0
    all_tags = {}
    grayware_tag_found = False
    grayware_count = 0
    tags = app["tags"]

    for tag in tags:
        classification = tag["tag"]
        category = tag["category"]
        count = tag["count"]
        if category == "CLASS":# or category == "FAM":

            if count > top_tag_count and classification != "grayware":
                top_tag = classification
                top_tag_count = count

            if classification == "grayware":
                grayware_tag_found = True
                grayware_count = count

            all_tags[classification] = count

    if top_tag == '':
        if grayware_tag_found:
            # Only tag as grayware if it's the only tag
            top_tag = "grayware"
            top_tag_count = grayware_count
        else:
            top_tag = "no tag"

    return { "top" : top_tag, "all" : all_tags }


def get_label_stats(apps):
    all_tags = {} # All tags from all apps, grouped by name
    top_tags = {} # Tag counts based on top tag per each app (excluding grayware)

    for app in apps:
        app_tags = get_labels(app)

        if app_tags["top"] not in top_tags:
            top_tags[app_tags["top"]] = 1
        else:
            top_tags[app_tags["top"]] += 1

        for tag in app_tags["all"]:
            if tag not in all_tags:
                all_tags[tag] = 1
            else:
                all_tags[tag] += 1

    return { "top_tags" : top_tags, "all_tags" : all_tags }


class ApiError(Exception):
    pass
# Load API key # return response.json() # Return content deserialized to a dictionary # Return raw content bytes # Combine a folder of VT files into one compatible with AVClass2 # Run avclass2 and return the resulting label array # Get app from avclass result by sha256 value. # We do this by looking up the file name from the json dir, which is *sha256*.json # In the file we get the MD5 of the app, which is what AVClass2 uses in its result. # Extract the labels of a single app # or category == "FAM": # Only tag as grayware if it's the only tag # All tags from all apps, grouped by name # Tag counts based on top tag per each app (excluding grayware)