import cv2
import numpy as np
import sys
from pathlib import Path
import glob
import os
import time
import datetime
from datetime import datetime, date , timedelta
import os.path
# import asyncio
# import telegram


# my_token = '5522894419:AAE9CeONlV2lfmUGqbXGZAHC-l1Z90TMuD4'

# async def send(msg, chat_id, token=my_token):
#     """
#     Send a message to a telegram user or group specified on chatId
#     chat_id must be a number!
#     """
#     bot = telegram.Bot(token=token)
#     bot.sendMessage(chat_id=chat_id, text=msg)


import json
def read_json_file(path_file:str="data.json"):
    # Opening JSON file
    f = open(path_file)
    # returns JSON object as a dictionary
    data = json.load(f)
    # Closing file
    f.close()
    return data
def search(data, search:str, default:str):
    """ search for specific keys """
    search_ret = []
    if isinstance(data, (list, tuple)):
        for d in data:
            for key in d.keys():
                if key == search:
                    try:
                        search_ret.append(d[key])
                    except (KeyError, ValueError, IndexError, TypeError, AttributeError):
                        pass
    else:
        for key in data.keys():
            if key == search:
                try:
                    search_ret.append(data[key])
                except (KeyError, ValueError, IndexError, TypeError, AttributeError):
                    pass
    if search_ret:
        val = search_ret
    else:
        val = default
    return val
# Function : update the json file with the new data and save it
# Attributes:
#   - data: the json data
#   - update_key: the key to update
#   - value: the new value
#   - saved_path: the path to the json file
# Returns:
#   - data: the updated json data
def update(data, update_key:str, value:str, saved_path:str="data.json"):
    """ update a specific key """
    # update the value of the key in the json data
    if isinstance(data, (list, tuple)):
        for d in data:
            for key in d.keys():
                if key == update_key:
                    try:
                        d[key] = value
                    except (KeyError, ValueError, IndexError, TypeError, AttributeError):
                        pass
    else:
        for key in data.keys():
            if key == update_key:
                try:
                    data[key] = value
                except (KeyError, ValueError, IndexError, TypeError, AttributeError):
                    pass

    # If the saved_path exists, we update it with the new data
    if saved_path:
        # Writing JSON data to file
        with open(saved_path, 'w') as f:
            json.dump(data, f)
    return data


filename = str(sys.argv[1])
##print('iframe detected:'+filename)
# iframe = cv2.imread(filename)
# iframe = cv2.imread(filename)
iframe = cv2.imread("iframes_live_old/"+filename)
# iframe = cv2.imread(filename)

#print("============================================================================")



def compare_image(image_1, image_2):
    start_time = time.time()
    # image_1=cv2.imread(image_1)
    # image_2=cv2.imread(image_2)
    first_image_hist = cv2.calcHist([image_1], [0], None, [256], [0, 256])
    second_image_hist = cv2.calcHist([image_2], [0], None, [256], [0, 256])

    img_hist_diff = cv2.compareHist(first_image_hist, second_image_hist, cv2.HISTCMP_BHATTACHARYYA)
    img_template_probability_match = cv2.matchTemplate(first_image_hist, second_image_hist, cv2.TM_CCOEFF_NORMED)[0][0]
    img_template_diff = 1 - img_template_probability_match

    # taking only 10% of histogram diff, since it's less accurate than template method
    commutative_image_diff = (img_hist_diff * 0.50) + img_template_diff
    end_time = time.time()
    # #print("Time taken to compare images in Seconds: {}".format(end_time - start_time))
    return commutative_image_diff


# def compare_image(image_1, image_2):
#     start_time = time.time()
#
#     first_image_hist = cv2.calcHist([image_1], [0], None, [256], [0, 256])
#     second_image_hist = cv2.calcHist([image_2], [0], None, [256], [0, 256])
#
#     img_hist_diff = cv2.compareHist(first_image_hist, second_image_hist, cv2.HISTCMP_BHATTACHARYYA)
#     img_template_probability_match = cv2.matchTemplate(first_image_hist, second_image_hist, cv2.TM_CCOEFF_NORMED)[0][0]
#     img_template_diff = 1 - img_template_probability_match
#
#     # taking only 10% of histogram diff, since it's less accurate than template method
#     commutative_image_diff = (img_hist_diff * 0.40) + img_template_diff
#     end_time = time.time()
#     # #print("Time taken to compare images in Seconds: {}".format(end_time - start_time))
#     return commutative_image_diff


# def compare_image_2(image_1, image_2, threshold=0.95):
#     # start timer for sift comparison
#     start_time = time.time()
#     # initialize sift
#     # create sift object to extract keypoints and descriptors from images
#     # sift = cv2.xfeatures2d.SIFT_create()
#     sift = cv2.SIFT()
#     # find keypoints and descriptors for both images
#     kp1, des1 = sift.detectAndCompute(image_1, None)
#     kp2, des2 = sift.detectAndCompute(image_2, None)
#     # create BFMatcher object to match descriptors
#     bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)
#     # match descriptors using kNN
#     matches = bf.match(des1, des2)
#     # sort matches in the order of their distance
#     matches = sorted(matches, key=lambda x: x.distance)
#     # calculate the number of matches
#     num_matches = len(matches)
#     # calculate the percentage of matches
#     percentage_matches = num_matches / len(kp2)
#     # end timer for sift comparison
#     end_time = time.time()
#     #print("Time taken to compare images in Seconds: {}".format(end_time - start_time))
#     # return the percentage of matches
#     return percentage_matches*100



jingle1_1 = cv2.imread("jingles_iframes/iframe_jingle1/jingle1_1.png")
jingle1_2 = cv2.imread("jingles_iframes/iframe_jingle1/jingle1_2.png")
jingle1_3 = cv2.imread("jingles_iframes/iframe_jingle1/jingle1_3.png")

jingle2_1 = cv2.imread("jingles_iframes/iframe_jingle2/jingle2_1.png")
jingle2_2 = cv2.imread("jingles_iframes/iframe_jingle2/jingle2_2.png")
jingle2_3 = cv2.imread("jingles_iframes/iframe_jingle2/jingle2_3.png")

jingle3_1 = cv2.imread("jingles_iframes/iframe_jingle3/jingle3_1.png")
jingle3_2 = cv2.imread("jingles_iframes/iframe_jingle3/jingle3_2.png")
jingle3_3 = cv2.imread("jingles_iframes/iframe_jingle3/jingle3_3.png")

jingle4_1 = cv2.imread("jingles_iframes/iframe_jingle4/jingle4_1.png")
jingle4_2 = cv2.imread("jingles_iframes/iframe_jingle4/jingle4_2.png")
jingle4_3 = cv2.imread("jingles_iframes/iframe_jingle4/jingle4_3.png")

jingle5_1 = cv2.imread("jingles_iframes/iframe_jingle5/jingle5_1.png")
jingle5_2 = cv2.imread("jingles_iframes/iframe_jingle5/jingle5_2.png")
jingle5_3 = cv2.imread("jingles_iframes/iframe_jingle5/jingle5_3.png")

jingle6_1 = cv2.imread("jingles_iframes/iframe_jingle6/jingle6_1.png")
jingle6_2 = cv2.imread("jingles_iframes/iframe_jingle6/jingle6_2.png")
jingle6_3 = cv2.imread("jingles_iframes/iframe_jingle6/jingle6_3.png")
# jingle6_1 = cv2.imread("iframes_live/index202207071657183034.1657183038_69_6.png")
# jingle6_2 = cv2.imread("jingles_iframes/iframe_jingle6/jingle6_2.png")
# jingle6_3 = cv2.imread("iframes_live_old/index140.1647943665_1_3.png")

jingles_time = {}
jingles_time["jingle_1"] = 7
jingles_time["jingle_2"] = 7
jingles_time["jingle_3"] = 6
jingles_time["jingle_4"] = 6
jingles_time["jingle_5"] = 8
#jingles_time["jingle_6"] = 6


frame_in_jingle = {}
frame_in_jingle["jingle_1"] = []
frame_in_jingle["jingle_1"].append(3)
frame_in_jingle["jingle_1"].append(4)
frame_in_jingle["jingle_1"].append(5) #######"" random

frame_in_jingle["jingle_2"] = []
frame_in_jingle["jingle_2"].append(2)
frame_in_jingle["jingle_2"].append(5)
frame_in_jingle["jingle_2"].append(6)  ########"" random

frame_in_jingle["jingle_3"] = []
frame_in_jingle["jingle_3"].append(1)
frame_in_jingle["jingle_3"].append(3)
frame_in_jingle["jingle_3"].append(3) #####" random"

frame_in_jingle["jingle_4"] = []
frame_in_jingle["jingle_4"].append(0)
frame_in_jingle["jingle_4"].append(3)
frame_in_jingle["jingle_4"].append(4)

frame_in_jingle["jingle_5"] = []
frame_in_jingle["jingle_5"].append(1)
frame_in_jingle["jingle_5"].append(2)
frame_in_jingle["jingle_5"].append(3)

frame_in_jingle["jingle_6"] = []
frame_in_jingle["jingle_6"].append(0)
frame_in_jingle["jingle_6"].append(4)
frame_in_jingle["jingle_6"].append(3)
# # frame_in_jingle["jingle_6"].append(4)

jingles_group = {}
jingles_group["jingle_1"] = []
jingles_group["jingle_1"].append(jingle1_1)
jingles_group["jingle_1"].append(jingle1_2)
jingles_group["jingle_1"].append(jingle1_3)

jingles_group["jingle_2"] = []
jingles_group["jingle_2"].append(jingle2_1)
jingles_group["jingle_2"].append(jingle2_2)
jingles_group["jingle_2"].append(jingle2_3)

jingles_group["jingle_3"] = []
jingles_group["jingle_3"].append(jingle3_1)
jingles_group["jingle_3"].append(jingle3_2)
jingles_group["jingle_3"].append(jingle3_3)

jingles_group["jingle_4"] = []
jingles_group["jingle_4"].append(jingle4_1)
jingles_group["jingle_4"].append(jingle4_2)
jingles_group["jingle_4"].append(jingle4_3)

jingles_group["jingle_5"] = []
jingles_group["jingle_5"].append(jingle5_1)
jingles_group["jingle_5"].append(jingle5_2)
jingles_group["jingle_5"].append(jingle5_3)

jingles_group["jingle_6"] = []
jingles_group["jingle_6"].append(jingle6_1)
jingles_group["jingle_6"].append(jingle6_2)
jingles_group["jingle_6"].append(jingle6_3)



i=0
last_frame_name = 'none'
last_frame_time = datetime.now()
now = datetime.now()
now_string = now.strftime("%Y-%m-%d %H:%M:%S")
now_string_api = str(now_string).replace(" ", "_")


lastHourDateTime = datetime.now() - timedelta(hours = 1)
lastHourDateTime_api = lastHourDateTime.strftime("%Y-%m-%d %H:%M:%S")
lastHourDateTime_api = str(lastHourDateTime_api).replace(" ", "_")


jing_n = 0




# #print('iframe detected:'+filename)
segment_file = "2m_hls/"+str(filename.split("_")[0])+".ts"
# #print("segment_file:"+segment_file)
lenght_seg = int(str(filename.split("_")[2]).replace(".png",""))
frame_in_seg = int(filename.split("_")[1])
time_in_seg = lenght_seg - int(float(frame_in_seg)/25)
time_to_cut = float(frame_in_seg)/25

# segment_file = filename.split("/")[1]
# segment_file = filename.split(".")[0]
# segment_file = segment_file+".ts"

#print("============================================================================")
#print("segment_file"+segment_file)

#############json
with open("check_two_min.json", "r+") as jsonFile:
    data1 = json.load(jsonFile)

current_date_time= datetime.now()

diff_in_seconds= (current_date_time - datetime.strptime(data1['start'].split('.')[0],"%Y-%m-%d %H:%M:%S")).total_seconds()

print('the difference time is :', diff_in_seconds)
if diff_in_seconds>120 and data1['is_request_sent']=="off" and diff_in_seconds<900:
    print('#################### HEEEEEEEEEEEEEEERE #######################')
    os.system("python3 api_request.py 1 "+str(current_date_time).replace(' ','_')+" "+str(round(diff_in_seconds))+" "+"limit_two_minutes")
    print('########" request is sent #######"')
    with open("check_two_min.json", "r+") as jsonFile:
        data1 = json.load(jsonFile)
    data1['is_request_sent']="on"

    jsonFile = open("check_two_min.json", "w+")
    jsonFile.write(json.dumps(data1))
    jsonFile.close()

#############

for jingles in jingles_group:
    jing_n +=1
    jingle_name = jingles
    index = 0
    for jingle in jingles_group[jingles]:
        # indexo = 1
        #print("jingles+index")
        print(str(jingles)+str(index))
        #
        #print("compare result")
        #print(str(compare_image(jingle,iframe)))



        print(str(compare_image(jingle,iframe)))
        # #print(str(jingles))
        ##print('the result of comparaison is ',compare_image(jingle,iframe))
        if float(compare_image(jingle,iframe)) < 0.1 and os.path.exists("iframes_live_old/"+filename):
           # asyncio.run(send("Similarity is detected","-1001778433367", token=my_token))
            path_file="data.json"
            data = read_json_file(path_file=path_file)

            with open("logs.txt",'a') as g:
                    g.write("================"+"\n")
                    g.write("Jingle "+str(filename)+"  detected at"+str(now_string_api)+"\n")


            os.system("cp iframes_live_old/"+filename+" jingles_found/")
            #print("jingles+index")
            #print(str(jingles)+str(index))
            #print("compare result")
            #print(str(compare_image(jingle,iframe)))

            start_J_end_seg = int(jingles_time[jingle_name]) - frame_in_jingle[jingle_name][index]
            now_start = datetime.now() - timedelta(seconds=time_in_seg) + timedelta(seconds=start_J_end_seg)
            now_start_string = now_start.strftime("%Y-%m-%d %H:%M:%S")

            end_J_start_seg = int(frame_in_jingle[jingle_name][index])
            now_end = datetime.now() - timedelta(seconds=time_in_seg) - timedelta(seconds=end_J_start_seg)
            now_end_string = now_end.strftime("%Y-%m-%d %H:%M:%S")


            # now_string_api = str(now_start_string).replace(" ", "_")


            with open('DAI_2m_hls/index.m3u8') as myFile:
                for num, line in enumerate(myFile, 1):
                    if segment_file in line:
                        pass




            file1 = open('last_live_jingle.txt', 'r')

            if os.stat("last_live_jingle.txt").st_size == 0:
            # if true:
                #print("================= Jingle Start at "+now_start_string)
                check = now_start_string+" --- "+jingle_name
                with open("logs.txt",'a') as g:
                    g.write("================"+"\n")
                    g.write("Jingle "+jingle_name+" number "+str(index)+" detected at"+now_start_string+"\n")
                    g.write("================"+"\n")
                    os.system("python3 adspot_api.py "+now_string_api+" this is a test of telegram")
                    g.close()
                # os.system("> last_live_jingle.txt")

                with open("last_live_jingle.txt",'w') as f:
                    f.write(now_start_string+" --- "+jingle_name+" --- start"+"\n")
                    f.close()
                    last_frame_time = now_start_string
                    last_frame_name = jingle_name
            else:


                for line in file1:
                    pass
                last_line = line
                if "---" in line:

                    line_arr = line.split(' --- ')
                    airtime0 = line_arr[0]
                    #print(line_arr[0])
                    last_frame_name = line_arr[1]
                    last_role = line_arr[2]
                    last_airtime = datetime.strptime(airtime0, '%Y-%m-%d %H:%M:%S')
                    #print("last_airtime:"+ str(last_airtime))
                    duration_since_last = now_end - last_airtime
                    duration_since_last = duration_since_last.total_seconds()
                    print("duration:"+str(duration_since_last))


                    # if round(duration_since_last) < 3 and last_frame_name == jingle_name:
                    if round(duration_since_last) < 3:
                        pass
                        #print("same jingle")

                    elif round(duration_since_last) > 10 and "end" in last_role:
                        ########## json
                        with open("check_two_min.json", "r+") as jsonFile:
                            data1 = json.load(jsonFile)

                        current_date_time=now = datetime.now()

                        data1['start']= current_date_time
                        data1['is_request_sent']="off"

                        jsonFile = open("check_two_min.json", "w+")
                        jsonFile.write(json.dumps(data1,default=str))
                        jsonFile.close()
                        print('initialization !!')
                        ############
                        with open("last_live_jingle.txt",'w') as f:
                            f.write(now_start_string+" --- "+jingle_name+" --- start"+"\n")
                            f.close()
                            last_frame_time = now_start_string
                            last_frame_name = jingle_name
                        # time_to_cut = time_to_cut - 0.2
                        #print("OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO")
                        # os.system("cp 2m_hls/"+segment_file+" temp_cutting/"+segment_file+"")
                        # os.system("ffmpeg -y -i 2m_hls/"+segment_file+" -ss 00 -t "+str(time_to_cut)+" -c copy temp_cutting/"+segment_file+"")
                        # os.system("ffmpeg -y  -i temp_cutting/"+segment_file+" -ss 00 -t "+str(time_to_cut)+" -c copy 2m_hls/"+segment_file+"")
                        # os.system("echo '#EXT-X-DISCONTINUITY' >> DAI_2m_hls/index.m3u8")
                        # os.system("echo '#EXTINF:3.160000,'  >> DAI_2m_hls/index.m3u8")
                        # os.system("echo '../jingles/jingle_1_0.ts'  >> DAI_2m_hls/index.m3u8")
                        # os.system("echo '#EXTINF:3.840000,'  >> DAI_2m_hls/index.m3u8")
                        # os.system("echo '../jingles/jingle_1_1.ts'  >> DAI_2m_hls/index.m3u8")
                        # os.system("echo '#EXT-X-DISCONTINUITY' >> DAI_2m_hls/index.m3u8")
                        # os.system("echo '#EXT-X-CUE-OUT' >> DAI_2m_hls/index.m3u8")
                        # #print("================> SCTE-35 start #tag")
                        # level = search(data, search="level", default="Attribute Not Found !")
                        # if level[0] > 1:
                        #     booked_adbreak_duration = search(data, search="adbreak_duration", default="Attribute Not Found !")
                        #     # os.system("echo '#EXTINF:120.000000,'  >> DAI_2m_hls/index.m3u8")
                        #     # os.system("echo '../samples/test_120.ts'  >> DAI_2m_hls/index.m3u8")
                        # update_result = update(data, update_key="inside_adbreak", value="yes", saved_path=path_file)



                    # elif round(duration_since_last) > 5 and round(duration_since_last) < 600 and "start" in last_role :
                    elif round(duration_since_last) > 6 and round(duration_since_last) < 600 :
                        adbreak_channel = "2M"
                        adbreak_start_at = last_airtime
                        adbreak_duration = int(duration_since_last)
                        booked_adbreak_duration = search(data, search="adbreak_duration", default="Attribute Not Found !")
                        current_debt = search(data, search="dept_in_seconds", default="Attribute Not Found !")
                        # if booked_adbreak_duration[0] - adbreak_duration > 0:
                        #     new_debt = current_debt[0] + booked_adbreak_duration[0] - adbreak_duration
                        #     new_debt = update(data, update_key="dept_in_seconds", value=new_debt, saved_path=path_file)
                        # os.system("cp 2m_hls/"+segment_file+" temp_cutting/"+segment_file+"")
                        # os.system("ffmpeg -y -ss "+str(time_to_cut)+" -i temp_cutting/"+segment_file+"  -c copy temp_cutting/_"+segment_file+"")
                        # os.system("echo '#EXT-X-DISCONTINUITY' >> DAI_2m_hls/index.m3u8")
                        # os.system("echo '#EXT-X-CUE-IN' >> DAI_2m_hls/index.m3u8")
                        # os.system("echo '#EXTINF:6.000000,'  >> DAI_2m_hls/index.m3u8")
                        # os.system("echo '../temp_cutting/_"+segment_file+"'  >> DAI_2m_hls/index.m3u8")
                        # os.system("echo '#EXT-X-DISCONTINUITY' >> DAI_2m_hls/index.m3u8")
                        if round(duration_since_last)<120:
                            print('ad break duration is :',str(duration_since_last))
                            print(' ad break duration is less than 40s')
                            with open("check_two_min.json", "r+") as jsonFile:
                                data1 = json.load(jsonFile)

                           # current_date_time=now = datetime.now()

                           # diff_in_seconds= (current_date_time - datetime.strptime(data['start'].split('.')[0],"%Y-%m-%d %H:%M:%S")).total_seconds()

                            #if diff_in_seconds>120 and data['is_request_sent']=="off":
                            os.system("python3 api_request.py 1 "+str(current_date_time).replace(' ','_')+" "+str(round(duration_since_last))+" "+"less_than_two_minutes")
                            #print('request sent by closing jingle !!')
                            data1['start']=current_date_time - timedelta(days = 1)

                            jsonFile = open("check_two_min.json", "w+")
                            jsonFile.write(json.dumps(data1,default=str))
                            jsonFile.close()

                        # if round(duration_since_last)>40:
                        #     print('ad break duration is :',str(duration_since_last))
                        #     with open("check_two_min.json", "r+") as jsonFile:
                        #         data1 = json.load(jsonFile)

                        #    # current_date_time=now = datetime.now()

                        #    # diff_in_seconds= (current_date_time - datetime.strptime(data['start'].split('.')[0],"%Y-%m-%d %H:%M:%S")).total_seconds()

                        #     #if diff_in_seconds>120 and data['is_request_sent']=="off":
                        #     os.system("python3 api_request.py 1 "+str(current_date_time)+" "+str(round(diff_in_seconds))+" "+"limit_two_minutes")
                        #     print('request sent by closing jingle !!')
                        #     data1['is_request_sent']="off"
                        #     data1['start']=current_date_time - timedelta(days = 1)

                        #     jsonFile = open("check_two_min.json", "w+")
                        #     jsonFile.write(json.dumps(data1,default=str))
                        #     jsonFile.close()

                        #print("================> SCTE-35 end #tag")
                        update_result = update(data, update_key="inside_adbreak", value="no", saved_path=path_file)



                        with open("logs.txt",'a') as g:
                            g.write("================"+"\n")
                            g.write("call to python functions  ")
                            g.write("Jingle "+jingle_name+" number "+str(index)+" detected at"+now_string+"\n")
                            g.write("duration: "+str(round(duration_since_last))+"\n")
                            g.write("================"+"\n")
                            g.close()

                        os.system("> last_live_jingle.txt")
                        with open("last_live_jingle.txt",'w') as f:
                            f.write(now_start_string+" --- "+jingle_name+" --- end"+"\n")
                            f.close()
                        # #print("python3 api_request.py 1 "+now_string_api+" "+str(round(duration_since_last)))
                        #os.system("python3 api_request.py 1 "+lastHourDateTime_api+" "+str(round(duration_since_last))+" "+jingle_name)
                        #print("call to python functions =======================================")

                    elif round(duration_since_last) > 800 :
                        #print("================= Jingle Start at "+now_start_string)
                        check = now_start_string+" --- "+jingle_name
                        os.system("python3 adspot_api.py "+now_string_api+" ngle")

                        with open("logs.txt",'a') as g:
                            g.write("================"+"\n")
                            g.write("Jingle Start at   ")
                            g.write("Jingle "+jingle_name+" number "+str(index)+" detected at"+now_start_string+"\n")
                            g.write("================"+"\n")
                            g.close()
                        os.system("> last_live_jingle.txt")

                        with open("last_live_jingle.txt",'w') as f:
                            f.write(now_start_string+" --- "+jingle_name+" --- start"+"\n")
                            f.close()
                            last_frame_time = now_start_string
                            last_frame_name = jingle_name

                    else:
                                # python send msg
                        #print("================= Jingle Start at "+now_start_string)
                        check = now_start_string+" --- "+jingle_name
                        os.system("python3 adspot_api.py "+now_string_api+" this is a test of telegram")

                        with open("logs.txt",'a') as g:
                            g.write("================"+"\n")
                            g.write("Jingle Start at   ")
                            g.write("Jingle "+jingle_name+" number "+str(index)+" detected at"+now_start_string+"\n")
                            g.write("================"+"\n")
                            g.close()
                        with open("last_live_jingle.txt",'w') as f:
                            f.write(now_start_string+" --- "+jingle_name+" --- start"+"\n")
                            f.close()
                            last_frame_time = now_start_string
                            last_frame_name = jingle_name

        index+=1
#
#
# blue_frame = cv2.imread("iframes_live_old/index202208311661949759_44_6.png")
# sabahiat_2m = cv2.imread("shows_iframes/sabahiat_2m/start/img1.png")
# moujaz_riyadi = cv2.imread("shows_iframes/moujaz_riyadi/start/img1.png")
# lilmatbakh_nojom = cv2.imread("shows_iframes/lilmatbakh_nojom/start/img1.png")
# kaifa_alhal = cv2.imread("shows_iframes/kaifa_alhal/start/index425.1653372603_15_6.png")
# journal_amazigh = cv2.imread("shows_iframes/journal_amazigh/start/img1.png")
# info_soir = cv2.imread("shows_iframes/info_soir/start/img1.png")
# al_wa3d = cv2.imread("shows_iframes/al_wa3d/start/img1.png")
# info_soir = cv2.imread("shows_iframes/info_soir/start/img1.png")
# que_du_sport = cv2.imread("shows_iframes/que_du_sport/start/img2.png")
#
# Auto_Moto = cv2.imread("shows_iframes/Auto-Moto/index45.1658573217_109_6.png")
# Bent_Bladi = cv2.imread("shows_iframes/Bent_Bladi/index3546.1658594222_141_6.png")
# Lalla_Fatema = cv2.imread("shows_iframes/Lalla_Fatema/index192.1658574098_24_6.png")
# # lilmatbakh_nojom = cv2.imread("shows_iframes/Lil_Matbakhi_Noujoum/index1872.1658584178_1_6.png")
# Min_Ajli_Ibni = cv2.imread("shows_iframes/Min_Ajli_Ibni/index3822.1658595878_17_6.png")
#
#
# carrefour = cv2.imread("iframes_live_old/index210.1648338262_65_6.png")
# orange = cv2.imread("iframes_live_old/index209.1648338255_73_6.png")
#
#
# if float(compare_image(blue_frame,iframe)) < 0.1:
#     #print("blue_frame" +str(compare_image(blue_frame,iframe)))
#     #print("python3 adspot_api.py "+now_string_api+" Blue_Frame")
#     os.system("python3 adspot_api.py "+now_string_api+" Blue_Frame")

# if float(compare_image(sabahiat_2m,iframe)) < 0.1 :
#
#     #print("python3 adspot_api.py "+now_string_api+" sabahiat_2m")
#     os.system("python3 adspot_api.py "+now_string_api+" Sabahiat_2M")
#
# #print(str(compare_image(info_soir,iframe)))
#
# if float(compare_image(info_soir,iframe)) < 0.1:
#         #print(str(compare_image(info_soir,iframe)))
#         os.system("python3 adspot_api.py "+now_string_api+" info_soir")
#
# if float(compare_image(que_du_sport,iframe)) < 0.1:
#     #print(str(compare_image(moujaz_riyadi,iframe)))
#     os.system("python3 adspot_api.py "+now_string_api+" que_du_sport")
#
# if float(compare_image(Auto_Moto,iframe)) < 0.1:
#     #print(str(compare_image(Auto_Moto,iframe)))
#     os.system("python3 adspot_api.py "+now_string_api+" Auto_Moto")
#
#
# if float(compare_image(Bent_Bladi,iframe)) < 0.1:
#     #print("compare bent bladi score:")
#     #print(str(compare_image(Bent_Bladi,iframe)))
#     os.system("python3 adspot_api.py "+now_string_api+" Bent_Bladi")
#
#
# if float(compare_image(Lalla_Fatema,iframe)) < 0.1:
#     #print(str(compare_image(Lalla_Fatema,iframe)))
#     os.system("python3 adspot_api.py "+now_string_api+" Lalla_Fatema")
#
#
# if float(compare_image(Min_Ajli_Ibni,iframe)) < 0.1:
#     #print(str(compare_image(Min_Ajli_Ibni,iframe)))
#     os.system("python3 adspot_api.py "+now_string_api+" Min_Ajli_Ibni")