from chromadb.errors import NoIndexException

from pilot.scene.base_chat import BaseChat, logger, headers
from pilot.scene.base import ChatScene
from pilot.common.sql_database import Database
from pilot.configs.config import Config

from pilot.common.markdown_text import (
    generate_markdown_table,
    generate_htm_table,
    datas_to_table_html,
)

from pilot.configs.model_config import (
    DATASETS_DIR,
    KNOWLEDGE_UPLOAD_ROOT_PATH,
    LLM_MODEL_CONFIG,
    LOGDIR,
)

from pilot.scene.chat_knowledge.v1.prompt import prompt
from pilot.embedding_engine.embedding_engine import EmbeddingEngine
from pilot.server.knowledge.service import KnowledgeService

CFG = Config()

class ChatKnowledge(BaseChat):
    chat_scene: str = ChatScene.ChatKnowledge.value()

    """Number of results to return from the query"""

    def __init__(self, chat_session_id, user_input, knowledge_space):
        """ """
        super().__init__(
            chat_mode=ChatScene.ChatKnowledge,
            chat_session_id=chat_session_id,
            current_user_input=user_input,
        )
        self.space_context = self.get_space_context(knowledge_space)
        self.top_k = (
            CFG.KNOWLEDGE_SEARCH_TOP_SIZE
            if self.space_context is None
            else int(self.space_context["embedding"]["topk"])
        )
        # self.recall_score = CFG.KNOWLEDGE_SEARCH_TOP_SIZE if self.space_context is None else self.space_context["embedding"]["recall_score"]
        self.max_token = (
            CFG.KNOWLEDGE_SEARCH_MAX_TOKEN
            if self.space_context is None
            else int(self.space_context["prompt"]["max_token"])
        )
        vector_store_config = {
            "vector_store_name": knowledge_space,
            "vector_store_type": CFG.VECTOR_STORE_TYPE,
            "chroma_persist_path": KNOWLEDGE_UPLOAD_ROOT_PATH,
        }
        self.knowledge_embedding_client = EmbeddingEngine(
            model_name=LLM_MODEL_CONFIG[CFG.EMBEDDING_MODEL],
            vector_store_config=vector_store_config,
        )

    def generate_input_values(self):
        try:
            if self.space_context:
                self.prompt_template.template_define = self.space_context["prompt"][
                    "scene"
                ]
                self.prompt_template.template = self.space_context["prompt"]["template"]
            docs = self.knowledge_embedding_client.similar_search(
                self.current_user_input, self.top_k
            )
            context = [d.page_content for d in docs]
            context = context[: self.max_token]
            input_values = {"context": context, "question": self.current_user_input}
        except NoIndexException:
            raise ValueError(
                "you have no knowledge space, please add your knowledge space"
            )
        return input_values

    @property
    def chat_type(self) -> str:
        return ChatScene.ChatKnowledge.value()

    def get_space_context(self, space_name):
        service = KnowledgeService()
        return service.get_space_context(space_name)


#!/usr/bin/env python3.7
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 11 11:14:12 2019

@author: ejreidelbach

:DESCRIPTION:

:REQUIRES:

:TODO:
"""

#==============================================================================
# Package Import
#==============================================================================
import json
import os
import pandas as pd
import pathlib
import tqdm
import urllib.request

#==============================================================================
# Reference Variable Declaration
#==============================================================================

#==============================================================================
# Function Definitions
#==============================================================================
def downloadPictures(dict_url, folder_name):
    '''
    Purpose: Download pictures via the provided url for the image

    Inputs
    ------
        dict_url : dictionary of URLs
            dictionary in which the name of the image is the key and the
            associated value is the URL of the image
        folder_name : string
            name of the folder in which downloaded images should be stored

    Outputs
    -------
        files are saved to a folder named after the input dictionary
    '''
    # Check to see if the desired folder exists and create it if it doesn't
    pathlib.Path('pictures/',folder_name).mkdir(parents=True, exist_ok=True)

    # Download all the images at the associated URLs
    for name, url in tqdm.tqdm(dict_url.items()):
        if not pd.isna(url):
            urllib.request.urlretrieve(url, 'pictures/' + folder_name + '/'
                                       + name + '.jpg')

#==============================================================================
# Working Code
#==============================================================================

# Set the project working directory
path_dir = pathlib.Path('/home/ejreidelbach/Projects/draft-gem/src/static')
os.chdir(path_dir)

#------------------------------------------------------------------------------
# Download Pictures of Schools
#------------------------------------------------------------------------------
# Ingest the listing of schools and their associated pictures
df_pics_school = pd.read_csv('positionData/school_pictures.csv')
df_pics_school.set_index('school', drop=True, inplace=True)

# Convert the dataframe to a dictionary
dict_pics_school = df_pics_school.to_dict('index')
for key, value in dict_pics_school.items():
    dict_pics_school[key] = value['urlSchool']

# Download the pictures
downloadPictures(dict_pics_school, 'School')

#------------------------------------------------------------------------------
# Download Pictures of Quarterbacks
#------------------------------------------------------------------------------
# Ingest the Quarterback data
df_pics_qb = pd.read_csv('positionData/QB/pos_QB_final.csv')

# Rename the `pictureSchool` and `picturePlayer` variables to include URL
df_pics_qb.rename(columns = {'picturePlayer':'picturePlayerURL',
                             'pictureSchool':'pictureSchoolURL'}, inplace=True)

# Create the `pictureSchoolPath` and `picturePlayerPath` variables to map
#   the file location of the associated images (i.e. /positionData/pictures/..)
df_pics_qb['picturePlayerPath'] = df_pics_qb.apply(
        lambda row: '/positionData/pictures/QB/' + row['unique_id'] + '.png'
        if not pd.isnull(row['picturePlayerURL']) else '', axis = 1)
df_pics_qb['pictureSchoolPath'] = df_pics_qb['School'].apply(
        lambda x: '/positionData/pictures/School/' + x + '.png')

# Convert the dataframe to a dictionary
dict_pics_qb = df_pics_qb.to_dict('index')

# Write the updated data (with paths to pictures vice URLs) to a .csv file
#   ('pos_POSITION_final_pics.csv')
df_pics_qb.to_csv('positionData/QB/pos_QB_final_pics.csv', index = False)

# Write the updated data (with paths to pictures vice URLs) to a .json file
#   ('pos_POSITION_final_pics.json')
with open('positionData/QB/pos_QB_final_pics.json', 'wt') as out:
    json.dump(dict_pics_qb, out, sort_keys=True)

# Minimize the QB Dictionary for the purposes of picture scraping
dict_pics_qb_small = {}
for key, value in dict_pics_qb.items():
    dict_pics_qb_small[dict_pics_qb[key]['unique_id']] = value['picturePlayerURL']

# Download the pictures
downloadPictures(dict_pics_qb_small, 'QB')


from setuptools import find_packages, setup
from glob import glob
package_name = 'hb_task_1b'

setup(
    name=package_name,
    version='0.0.0',
    packages=find_packages(exclude=['test']),
    data_files=[
        ('share/ament_index/resource_index/packages',
            ['resource/' + package_name]),
        ('share/' + package_name, ['package.xml']),
        ('share/' + package_name + '/launch', glob('launch/*.launch.py')),
        ('share/' + package_name + '/urdf', glob('urdf/*.xacro')),
        ('share/' + package_name + '/meshes', glob('meshes/*')),
        ('share/' + package_name + '/worlds', glob('worlds/*')),
    ],

    install_requires=['setuptools'],
    zip_safe=True,
    maintainer='aniket',
    maintainer_email='aniket@todo.todo',
    description='TODO: Package description',
    license='TODO: License declaration',
    tests_require=['pytest'],
    entry_points={
        'console_scripts': [
            'controller = hb_task_1b.controller:main',
            'service_node = hb_task_1b.service_node:main',
        ],
    },
)


# challenge7.py

from Crypto.Cipher import AES
from Crypto import Random
import cryptotools as ct

with open('7.txt') as fo:
	encrypted = fo.read()

key = b'YELLOW SUBMARINE'

cipher = AES.new(key, AES.MODE_ECB)

encrypted_bytes = ct.base64_to_bytes(encrypted)
msg = cipher.decrypt(encrypted_bytes)

with open('7_decrypted.txt', 'w') as f:
    print(msg, file=f)


import os
import shutil
import time
from datetime import datetime

'''
Put this python file in another directorty or result may cause problem
'''

def folder_maker(folder_path):
    """
    Moves the files in the directory of the modified time
    """
    if os.getcwd() == folder_path:
        print("folder path invalid")
    else:
        os.chdir(folder_path)
        for i in os.listdir():
            path = os.path.join(folder_path, i)
            ti = (datetime.fromtimestamp(os.path.getmtime(path)))
            c_ti = str(ti.strftime('%Y-%m-%d'))
            f_path = os.path.join(folder_path, c_ti)
            if not os.path.exists(f_path):
                os.makedirs(f_path)
            source = os.path.join(folder_path, i)
            destination = os.path.join(folder_path, f_path)
            test = shutil.move(source, destination)

folder_maker()


##_Pico W weather sation with Mongodb and BMP280 sensor
##_by ArturCr
##_10/09/2022

##_Libraries
import machine
import urequests as requests
import network
import rp2
import time
##_Library required for bme280
import bme280

##_A file called secrets.py is required with the following data...
from secrets import secrets as s
SSID = s['ssid']
PSK = s['pw']
COUNTRY = s['country']
API_KEY = s['api-key']
URL_ENDPOINT = s['url-endpoint']
CLUSTER = s['cluster']
DATABASE = s['database']
COLLECTION = s['collection']
STATION_NAME  = "Pico_Station_0"

##_Led pattern on powerup
led = machine.Pin('LED', machine.Pin.OUT)
led.toggle()
time.sleep(.75)
led.off()

##_Provides time to avoid reset loops but allows for clean network reconnection
def reset_protocol():
    for x in range(50):
        led.toggle()
        time.sleep(.2)
    led.on()
    time.sleep(1)
    machine.reset()

##_Configure the Wifi card to use the frequencies available for that geography
rp2.country(COUNTRY)

##_Connects to wifi using the provided credentials otherwise reboot pico
def connect_to_wifi(ssid, psk):
    ##_Enable Wifi in Client Mode
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    ##_Connect to Wifi, keep trying until failure or success
    wlan.connect(ssid, psk)

    while not wlan.isconnected() and wlan.status() >= 0:
        print("Waiting to Connect")
        time.sleep(5)
    if not wlan.isconnected():
        #raise Exception("Wifi not available")
        print("Wifi not available")
        reset_protocol()
    print("Connected to WiFi")

##_Discconect from wifi to safe on power
def disconnect_to_wifi():
    ##_Stop the Wifi
    try:
        wlan = network.WLAN(network.STA_IF)
        wlan.disconnect()
        wlan.active(False)
    except Exception as e:
        print('try 2: ',e)

##_Get weather data from bme280 sensor
Data_to_send=[]
def get_bme280_readings():
    data_to_send=[]

    ##_Power on sensor
    power = machine.Pin(2, machine.Pin.OUT)
    power.on()
    time.sleep(1)

    ##_Commuticate over I2C
    i2c = machine.I2C(0,scl=machine.Pin(1), sda=machine.Pin(0))
    bme = bme280.BME280(i2c=i2c)

    for x in range (6):
        print(bme.values)
        ##Temperature(C) Pressure(-1000) and Humidity(%)
        data_to_send.append({'Temperature':float(bme.values[0][:-1]),'Pressure':float(bme.values[1][:-3])-1000.0,'Humidity':float(bme.values[2][:-1]),'timestamp':formated_datetime()})
        time.sleep(2)

    print(data_to_send)
    return data_to_send

##_Real time clock
rtc = machine.RTC()
def set_RTC():
    #connect_to_wifi(SSID, PSK)
    ##_Make GET request to server with time data
    while True:
        try:
            ##Getting time data from "http://date.jsontest.com"
            r = requests.get("http://date.jsontest.com", timeout=10)
            break
        except:
            print('.',end='')
            time.sleep(1)

    date_and_time = r.json()
    r.close()

    print(date_and_time)

    H24_clock_offset=0
    if date_and_time['time'][9:]=='PM':
        H24_clock_offset=12
    hour=int(date_and_time['time'][:2])+H24_clock_offset

    rtc.datetime((int(date_and_time['date'][6:]),
                  int(date_and_time['date'][:2]),
                  int(date_and_time['date'][3:5]),
                  0,
                  int(hour),
                  int(date_and_time['time'][3:5]),
                  int(date_and_time['time'][6:8]),
                  1))
    #disconnect_to_wifi()

##_Reformat data for the database to be able to read it
def formated_datetime():
    a=rtc.datetime()
    return str(a[0])+'-'+str(a[1])+'-'+str(a[2])+'T'+str(a[4])+':'+str(a[5])+':'+str(a[6])

def send_data_out():
    #connect_to_wifi(SSID, PSK)

    url = URL_ENDPOINT + "/action/insertOne"
    headers = { "api-key": API_KEY}

    documentToAdd = {"device": STATION_NAME , "v": Data_to_send}

    insertPayload = {
        "dataSource": CLUSTER,
        "database": DATABASE,
        "collection": COLLECTION,
        "document": documentToAdd,
    }

    print("sending...")

    response = requests.post(url, headers=headers, json=insertPayload, timeout=10)

    print("Response: (" + str(response.status_code) + "), msg = " + str(response.text))

    if response.status_code == 201:
        print("Added Successfully")
        led.toggle()
        time.sleep(.25)
        led.toggle()
    else:
        print("Error")

    ##_Always close response objects so we don't leak memory
    response.close()
    time.sleep(.01)

##_Main Loop
try:
    connect_to_wifi(SSID, PSK)

    set_RTC()

    print(formated_datetime())

    Data_to_send=get_bme280_readings()

    send_data_out()

    disconnect_to_wifi()

except Exception as e:
    print('Main code loop error: ',e)

disconnect_to_wifi()
print("Entering deepsleep 60 sec")
machine.deepsleep(60*1000)#Deepsleep for x secounds


from sqlalchemy import Enum

from app.api.invoices.models import InvoiceMapper
from app.api.shared.models.approval_status import ApprovalStatus
from app.common.external_api.administration_api import CompanyInfo
from app.core.mapper import ApiMapper, Payload, Entity
from app.infra.db import Column, Model, SurrogatePK, db, reference_col
from .bill_status import BillStatus
from .dto import BillDTO, DetailedBillDTO

class Bill(Model, SurrogatePK):
    __tablename__ = 'bills'

    invoice_id = reference_col('invoices')
    invoice = db.relationship('Invoice', foreign_keys=[invoice_id], back_populates='bill')
    payment_method_id = Column(db.BigInteger, nullable=True)
    status = Column(Enum(BillStatus), nullable=False)
    approval_status = Column(Enum(ApprovalStatus), nullable=False)
    bill_cancellation = db.relationship('BillCancellation', uselist=False, back_populates='bill')

    def __init__(self, invoice_id, status=BillStatus.Unpaid,
                 approval_status=ApprovalStatus.NotSet):
        self.invoice_id = invoice_id
        self.status = status
        self.approval_status = approval_status

class BillMapper:
    companies: list[CompanyInfo]

    def __init__(self, companies: list[CompanyInfo] = None):
        if companies is None:
            companies = []
        self.companies = companies

    def to_dto(self, entity: Bill) -> BillDTO:
        bill_company = None
        for company in self.companies:
            if company.id == entity.invoice.buyer_id:
                bill_company = company
                break

        return BillDTO(
            id=entity.id,
            invoiceId=entity.invoice_id,
            invoiceNumber=entity.invoice.number,
            dueDate=entity.invoice.due_date,
            createdDate=entity.invoice.created_date,
            paymentMethod='',
            paymentMethodId=entity.payment_method_id,
            status=entity.status.name,
            companyName=bill_company.name if bill_company else '',
            companyLogo=bill_company.logo if bill_company else '',
            companyId=bill_company.id if bill_company else 0,
            amount=entity.invoice.total,
            currency=entity.invoice.currency.name,
        )

class DetailedBillMapper(ApiMapper):
    @staticmethod
    def to_entity(payload: Payload) -> Entity:
        raise NotImplemented

    @staticmethod
    def to_dto(entity: Bill) -> DetailedBillDTO:
        return DetailedBillDTO(
            id=entity.id,
            status=entity.status.name,
            approvalStatus=entity.approval_status.name,
            paymentMethodId=entity.payment_method_id,
            invoice=InvoiceMapper.to_dto(entity.invoice),
            buyer=None,
            seller=None
        )


from config.db import meta
from sqlalchemy import Table, Column
from sqlalchemy.sql.sqltypes import Integer, String

tab_users=Table(
    'tab_users',meta,
    Column('id', Integer, primary_key=True),
    Column('nome', String(100)),
    Column('email', String(100), unique=True),
    Column('senha', String(50)),
    Column('departamento', String(50))
  )


from os import remove
from glob import glob
import json

from supp.utils import create_sstable_filename, get_sstable_pattern

def list_sstables():
    '''
    Lists all sstables (path names)
    '''
    return glob(get_sstable_pattern('json'))

def read_sstable(filename):
    '''
    Reads sstable from file
    '''
    fin = open(filename, 'rt' )
    sstable_json = fin.read()
    fin.close()

    sstable = {}
    for record in json.loads(sstable_json):
        sstable[record['key']] = record

    return sstable

def write_sstable(memtable):
    '''
    Writes memtable to sstable in file
    '''
    filename = create_sstable_filename('json')
    memtable_json = json.dumps(list(memtable.values()), indent=4)
    fout = open(filename, 'wt' )
    fout.write(memtable_json)
    fout.close()

def delete_sstables():
    '''
    Deletes all sstable files
    '''
    for filename in list_sstables():
        remove(filename)


from flask import Flask, render_template, request, make_response, send_from_directory, redirect, jsonify
import random
import string
import os
import time

import multiprocessing as mp

def uuid(n=20):
  return ''.join(random.sample(string.ascii_letters + string.digits, n))
app = Flask(__name__)

ROOT = os.getcwd()
SHAREROOT = os.path.join(ROOT, "shared")

def add_removal(did, internal = 15*60, dir_ = "remove.txt"):
  with open(os.path.join(ROOT, dir_),"a", encoding="utf-8") as f:
    f.write("{} {}\n".format(did, time.time()+internal))

class Share(object):
  def __init__(self, did, internal = 15*60):
    self.did = did
    self.didRoot = os.path.join(SHAREROOT, did)
    if not os.path.isdir(self.didRoot):
      os.mkdir(self.didRoot)
    self.txtFile = os.path.join(self.didRoot, "temp.txt")

  def writeFiles(self, files):
    with open(self.txtFile,"a", encoding="utf-8") as f:
      for file_ in files:
        file_.save("{}/{}".format(self.didRoot, file_.filename))
        f.write("{} {}\n".format(file_.filename, "/download/{}/{}".format(self.did, file_.filename)))

@app.route('/')
@app.route('/index')
def index():
    return render_template('index.html', title="Home", home_status="active")

@app.route('/upload')
def upload_file():
   return render_template('upload.html', title="Upload", configer=True, upload_status = "active")

@app.route('/download')
def download():
   return render_template('download.html', title="Download", download_status = "active")

@app.route('/list_from_code',methods=['GET',"POST"])
def list_from_code():
  if request.method == 'POST':
    did = request.form.get('code')
    return redirect("/listfiles/"+did)
  return render_template('download.html', title="Download",download_status = "active")

@app.route('/listfiles/<did>')
def listfiles(did):
  if not os.path.isfile(SHAREROOT+"/{}/temp.txt".format(did)):
    return render_template('download.html', title="Download", download_status = "active", alertMSG = "Code NOT Valid")
  files=[]
  with open(SHAREROOT+"/{}/temp.txt".format(did),"r", encoding="utf-8") as f:
    for line in f.readlines():
      name, url = line.split(" ")
      files.append((name.strip(),url.strip()))
  return render_template('filelist.html', title="Download", download_status="active", data = {"files":files})

@app.route("/download/<did>/<filename>", methods=['GET'])
def download_file(did,filename):
    response = make_response(send_from_directory(os.path.join(SHAREROOT,did), filename, as_attachment=True))
    response.headers["Content-Disposition"] = "attachment; filename={}".format(filename.encode().decode('latin-1'))
    return response

@app.route("/configer", methods=["POST"])
def configer():
  if request.method == "POST":
    getDid, getTime = request.form.get("did"), request.form.get("time")
    if not getTime:
      getTime = 15
    getTime = int(float(getTime))
    if not getDid:
      getDid = uuid()
    while os.path.isdir(SHAREROOT+"/"+getDid):
        getDid = getDid+uuid(4)
    add_removal(getDid, getTime*60)
    return render_template('upload.html', title="Upload", upload=True, upload_status = "active", didUrl=getDid)
  return render_template('upload.html', title="Upload", configer=True, upload_status = "active")

@app.route('/uploader', methods=['GET', 'POST'])
def uploader():
  if request.method == 'POST':
    try:
      getDid = request.form.get("did")
      share = Share(getDid)
      filenames = request.files.getlist('file')
      share.writeFiles(filenames)
      res = jsonify({"imgUrl": ",".join([x.filename for x in filenames]), "didUrl":getDid, "msg":"success"})
      return res
    except Exception as e:
      return str(e)
  return render_template('upload.html', title="Upload", upload=True, upload_status = "active")

if __name__ == '__main__':
  app.run(host='127.0.0.1', port=8080, debug=True, threaded=True)


import sys
sys.path.append("/usr/lib/python3.7/")
#import tensorflow as tf

import platform
import cv2
from threading import Thread
from video_stream import VideoStream
from datetime import datetime
import datetime
import time
import numpy as np
import os
from detector_cv2 import Detector
from picamera.array import PiRGBArray
from picamera import PiCamera
from database_manager import DatabaseManager
import pymongo
import ast
import tensorflow as tf
import nms

SSD_MOBILENET_V2_SAVED_MODEL_PATH="/home/pi/Desktop/My_Server/backend/models/"
category_map = {
    1: 'person',
    2: 'bicycle',
    3: 'car',
    4: 'motorcycle',
    5: 'airplane',
    6: 'bus',
    7: 'train',
    8: 'truck',
    9: 'boat',
    10: 'traffic light',
    11: 'fire hydrant',
    13: 'stop sign',
    14: 'parking meter',
    15: 'bench',
    16: 'bird',
    17: 'cat',
    18: 'dog',
    19: 'horse',
    20: 'sheep',
    21: 'cow',
    22: 'elephant',
    23: 'bear',
    24: 'zebra',
    25: 'giraffe',
    27: 'backpack',
    28: 'umbrella',
    31: 'handbag',
    32: 'tie',
    33: 'suitcase',
    34: 'frisbee',
    35: 'skis',
    36: 'snowboard',
    37: 'sports ball',
    38: 'kite',
    39: 'baseball bat',
    40: 'baseball glove',
    41: 'skateboard',
    42: 'surfboard',
    43: 'tennis racket',
    44: 'bottle',
    46: 'wine glass',
    47: 'cup',
    48: 'fork',
    49: 'knife',
    50: 'spoon',
    51: 'bowl',
    52: 'banana',
    53: 'apple',
    54: 'sandwich',
    55: 'orange',
    56: 'broccoli',
    57: 'carrot',
    58: 'hot dog',
    59: 'pizza',
    60: 'donut',
    61: 'cake',
    62: 'chair',
    63: 'couch',
    64: 'potted plant',
    65: 'bed',
    67: 'dining table',
    70: 'toilet',
    72: 'tv',
    73: 'laptop',
    74: 'mouse',
    75: 'remote',
    76: 'keyboard',
    77: 'cell phone',
    78: 'microwave',
    79: 'oven',
    80: 'toaster',
    81: 'sink',
    82: 'refrigerator',
    84: 'book',
    85: 'clock',
    86: 'vase',
    87: 'scissors',
    88: 'teddy bear',
    89: 'hair drier',
    90: 'toothbrush'
}
img_width=300
img_height=300

class DetectionManager:
    def __init__(self):
        self.model_paths = {"SSD_Mobilenet_v2_320x320":"/home/pi/Desktop/My_Server/backend/models/"}
        self.category_maps = {"SSD_Mobilenet_v2_320x320":{1: "person"}}

    def setupDetection(self, detection_period_id, neuralNetworkType="SSD_Mobilenet_v2_320x320", detectionSeconds=60,  obj_threshold=0.3,
                       video_resolution={"width":320, "height":320}, framerate=30):
        #TU SPRAWDZIC
        self.neuralNetworkType = neuralNetworkType
        self.obj_threshold = obj_threshold
        self.detectionSeconds = detectionSeconds
        self.video_resolution = video_resolution
        self.framerate = framerate
        self.detector = Detector("SSD_Mobilenet_v2_320x320")
        self.database_manager = DatabaseManager()
        #print("In setupDetection: " + str(detection_period_id))
        self.detection_period_id = detection_period_id
        #print("Starting detection: " + str(datetime.datetime.now()))
        detections = self.detect()
        #print("Ending detection: " + str(datetime.datetime.now()))

    def detect(self):
        resolution={"width":1200, "height":720}
        framerate=30
        camera = PiCamera()
        camera.rotation = 180
        camera.resolution = (resolution["width"], resolution["height"])
        camera.framerate = framerate
        rawCapture = PiRGBArray(camera, size = (resolution["width"], resolution["height"]))
        print("I am alive")
        detections = self.detect()
        file = open("test_file", "w")
        now = datetime.now()
        current_time = now.strftime("%H:%M:%S")
        file.write("Active on: " + str(current_time))
        file.close()
        start_time = time.time()
        #video_stream = VideoStream(self.video_resolution, self.framerate)

        #video_stream.start()
        detection_results = None
        '''
        xml_file = '/home/pi/Desktop/My_Server/backend/endpoints/haarcascades/haarcascade_frontalface_default.xml'
        classifier = cv2.CascadeClassifier(xml_file)
        '''
            #frame = video_stream.read()
        for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):

            # Otherwise, grab the next frame from the stream
            img = frame.array

            rawCapture.truncate(0)

            #detection_results = self.detector.detect(frame, self.video_resolution["width"], self.video_resolution["height"])
            '''
            selected_indices = tf.image.non_max_suppresion(
                boxes=detection_results['detection_boxes'][0],
                scores=detection_results['detection_scores'][0],
                max_output_size=10,
                iou_threshold=0.5,
                score_threshold=0.2
                )

            selected_boxes = tf.gather(detection_results['detection_boxes'][0], selected_indices)
            '''

            #print("How many detected boxes were created: " + str(len(detection_results['detection_boxes'][0].numpy())))

            #selected_boxes = nms.non_max_suppression_fast(detection_results['detection_boxes'][0].numpy(), 0.4)
            '''
            selected_boxes = detection_results['detection_boxes'][0]

            for box in selected_boxes:
                frame = cv2.rectangle(frame, (int(box[1] * resolution["width"]), int(box[0] * resolution["height"])),
                                          (int(box[3] * resolution["width"]), int(box[2] * resolution["height"])), (0, 255, 0), 2)

            for box, score, det_class in zip(detection_results['detection_boxes'][0], detection_results['detection_scores'][0], detection_results['detection_classes'][0]):
                 if score > 0.2 and int(det_class) == 1:
                    frame = cv2.rectangle(frame, (int(box[1] * resolution["width"]), int(box[0] * resolution["height"])),
                                          (int(box[3] * resolution["width"]), int(box[2] * resolution["height"])), (255, 0, 0), 2)
            '''
            '''
            gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

            faces_rect = classifier.detectMultiScale(
                gray_img, scaleFactor=1.1, minNeighbors=9)

            for (x, y, w, h) in faces_rect:
                frame = cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), thickness=2)
            '''
            number_of_people = self.detector.detect_cv2(img)

            #print(detection_results)

            #cv2.imwrite('\home\pi\Desktop\my_img', frame)
            current_time = time.time()
            elapsed_time = current_time - start_time

            #detection_objects.append({"frame_time":current_time, "detections":predicted_boxes})
            self.database_manager.insertDetection(current_time, number_of_people, self.detection_period_id)

            if elapsed_time > self.detectionSeconds:
                #self.writeDetectionPeriodSummary(detection_objects, start_time, self.detectionSeconds)
                '''
                for det_obj in detection_objects:
                    for fin_box in det_obj:
                        print("detection_object: " + str(fin_box.classes[0]))
                '''
                break

        camera.stop_preview()
        camera.close()
        cv2.destroyAllWindows()
        #videostream.stop()

        #return final_boxes
        '''

    def determineSecondsForDetection(self, detectionTimeString):
        timeValues = []
        timeValues = detectionTimeString.split(':')
        for timeVal in timeValues:
            print("Time value: " + timeVal)
        timeNow = datetime.datetime.now().time()
        hours = int(timeValues[0]) - timeNow.hour
        minutes = int(timeValues[1]) - timeNow.minute
        print("Hours: " + str(hours))
        print("Minutes: " + str(minutes))
        if minutes < 0:
            minutes = 60 - minutes
            hours -= 1

        if hours < 0:
            print("End time must be grater that start time !")
        start_time = time.time()

    def writeDetectionPeriodSummary(self, detections, timestamp, seconds_of_detection):
        f = open(self.PATH_TO_DETECTION_FILES + str(timestamp), "a")
        f.write("START:" + str(timestamp) + ":DURATION:" + str(seconds_of_detection) + "\n")
        for detection in detections:
            f.write("frame_time:" + str(detection["frame_time"]) + ":detections:" + str(detection["detections"]) + "\n")
        f.write("NUMBER_OF_DETECTIONS:" + str(len(detections)))
        f.close()

    def get_detection_data(self):
        detection_objects = []
        # iterate over files in
        # that directory
        for filename in os.listdir(self.PATH_TO_DETECTION_FILES):
            f = os.path.join(self.PATH_TO_DETECTION_FILES, filename)
            # checking if it is a file
            if os.path.isfile(f):
                myfile = open(f, "r")
                mylist = myfile.readlines()
                basic_info_array = mylist[0].split(':')
                print("Timestamp: " + basic_info_array[1])
                print("secondsOfDetection: " + basic_info_array[3])
                detection_object = {
                    "timestamp":basic_info_array[1],
                    "secondsOfDetection":basic_info_array[3],
                    "detections":mylist[1:len(mylist)-1],
                    "numberOfDetections":mylist[-1]
                    }
                myfile.close()
                return detection_object

                detection_objects.append(detection_object)
        return detection_objects
'''


from io import StringIO
import json
from unittest import TestResult
import requests
from http.cookies import SimpleCookie

headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:78.0) Gecko/20100101 Firefox/78.0",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Language": "en-US,en;q=0.5"
}

site_list = []
sites = []
total_cookies = 0
with open('sites.txt', 'r') as f:
    # Loops through each line (site) in file
    # and appends to sites_list
    for site in f:
        # Stripping newline from the string
        site_list.append(site.strip('\n'))

# Context manager to properly open and close file handle
with open('failed_sites.txt', 'w') as f:
    # Loop through each site in sites.txt
    for site in site_list:
         # Just declaring these to be used later. My naming is terrible
        samesite = 0
        lax = 0
        strict = 0
        ssnone = 0
        path_count = 0
        path_nondefault_count = 0
        http_only = 0
        secure = 0
        total_cookies = 0
        try:
            r = requests.head("http://"+site, timeout=60, headers=headers, allow_redirects=True)

            # Writes the HTTP response to the text file for this site
            with open('responses/' + site + '.txt', 'w') as response_file:
                r.history.append(r)
                for response in r.history:

                    # If this reponse does not set any cookies then continue to next response
                    if 'Set-Cookie' in response.headers:
                        cookies = response.headers['Set-Cookie']
                        total_cookies += len(response.raw.headers.getlist('Set-Cookie'))
                        samesite += cookies.count('SameSite')
                        lax += cookies.count('Lax')
                        strict += cookies.count('Strict')
                        ssnone += cookies.count('None')
                        path_count += cookies.count('path')
                        path_default = cookies.count('path=/')
                        path_nondefault_count += (path_count - path_default)
                        http_only += cookies.count('HttpOnly')
                        secure += cookies.count ('Secure')

                    response_file.write("HTTP/" + str(response.raw.version)[0] + "." + str(response.raw.version)[1] + " " + str(response.status_code) + " " + response.reason + '\n')
                    for item in response.headers:
                        if item == 'Set-Cookie':
                            for i in response.raw.headers.getlist('Set-Cookie'):
                                response_file.write('Set-Cookie: ' + i + '\n')
                            continue
                        response_file.write(item + ": " + response.headers[item] + '\n')
                    response_file.write('\n')

        # Catches potential exceptions for when a site takes too long to respond or some other error
        except requests.exceptions.RequestException as ex:
            f.write(site + ": " + str(ex) + '\n')
        sites.append(
                            {
                                'name': site,
                                'status_code': r.status_code,
                                'cookie_count': total_cookies,
                                'samesite_count': samesite,
                                'httponly_count': http_only,
                                'secure': secure,
                                'samesite_strict': strict,
                                'samesite_lax': lax,
                                'samesite_none': ssnone,
                                'path_count': path_count,
                                'path_nondefault_count': path_nondefault_count

                            }
                        )

# Writes the results to a json file to be read by table.py
with open('results.json', 'w') as f:
    json.dump(sites, f)


# import the necessary packages
from pyimagesearch.localbinarypatterns import LocalBinaryPatterns
from sklearn.svm import SVC
from imutils import paths
import argparse
import cv2
import os
import regex as re
from sklearn.metrics import classification_report, confusion_matrix, roc_curve, auc, roc_auc_score, accuracy_score
import pickle
from matplotlib import pyplot

# construct the argument parse and parse the arguments
#ap = argparse.ArgumentParser()
#ap.add_argument("-t", "--training", required=True,
#	help="path to the training images")
#ap.add_argument("-e", "--testing", required=True,
#	help="path to the tesitng images")
#args = vars(ap.parse_args())
# initialize the local binary patterns descriptor along with
# the data and label lists
desc = LocalBinaryPatterns(24, 3) #Era 24,3
data = []
labels = []
y_test = []
y_pred = []
y_pred_number = []
y_pred_proba = []
# loop over the training images
for imagePath in paths.list_images(os.getcwd()+"/images/training"):
	# load the image, convert it to grayscale, and describe it
	image = cv2.imread(imagePath)
	gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
	hist = desc.describe(gray)
	# extract the label from the image path, then update the
	# label and data lists
	labels.append(imagePath.split(os.path.sep)[-2])
	print(imagePath.split(os.path.sep)[-1])
	data.append(hist)
# train a Linear SVM on the data
for label in labels:
        print(label)

model = SVC(C=200, random_state=42, probability=True) #C era 200 / random_state era 42
model.fit(data, labels)

# loop over the testing images
for imagePath in paths.list_images(os.getcwd()+"/images/testing"):
	# load the image, convert it to grayscale, describe it,
	# and classify it
	image = cv2.imread(imagePath)
	#img = cv2.resize(image, (800, 800))
	gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
	hist = desc.describe(gray)
	prediction = model.predict(hist.reshape(1, -1))
	predictict_proba = model.predict_proba(hist.reshape(1, -1))

	#if prediction[0] == 'cataract':
	#	predNumber = 1
	#else:
	#	predNumber = 0

	if prediction == 'cataract':
		y_pred_number.append(1)
	else:
		y_pred_number.append(0)

	y_pred.append(prediction)
	y_pred_proba.append(predictict_proba)

	if re.search('\Acataract', imagePath.split(os.path.sep)[-1], re.IGNORECASE):
		y_test.append(1)
	else:
		y_test.append(0)

	print(imagePath.split(os.path.sep)[-1])
	#print(predNumber)

filename = 'finalized_model.sav'
pickle.dump(model, open(filename, 'wb'))

	# display the image and the prediction
	#cv2.putText(image, prediction[0], (10, 30), cv2.FONT_HERSHEY_SIMPLEX,
	#	1.0, (0, 0, 255), 3)
	#cv2.imshow("Image", image)
	#cv2.waitKey(0)

print("y_pred")
print(y_pred)

print("y_pred_proba")
print(y_pred_proba)

#ns_probs = [0 for _ in range(len(y_test))]

#ns_auc = roc_auc_score(y_test, ns_probs)
#lr_auc = roc_auc_score(y_test, y_pred_proba)

#print('No Skill: ROC AUC=%.3f' % (ns_auc))
#print('Logistic: ROC AUC=%.3f' % (lr_auc))

#ns_fpr, ns_tpr, _ = roc_curve(y_test, ns_probs)
#lr_fpr, lr_tpr, _ = roc_curve(y_test, y_pred_proba)

#pyplot.plot(ns_fpr, ns_tpr, linestyle='--', label='No Skill')
#pyplot.plot(lr_fpr, lr_tpr, marker='.', label='Logistic')

#pyplot.xlabel('False Positive Rate')
#pyplot.ylabel('True Positive Rate')

#pyplot.legend()

#pyplot.show()

#pyplot.savefig("grafico")

print("AUC Score = "+str(roc_auc_score(y_test, y_pred_number)))
print(confusion_matrix(y_test, y_pred_number))
print(classification_report(y_test, y_pred_number))


import numpy as np
import pandas as pd
import sklearn
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import cross_val_score
train = pd.read_csv("../input/train.csv")
train.shape
train.head()
train.dtypes.value_counts()
train.select_dtypes(include='object').columns
train2 = train.drop(columns = ['Id', 'idhogar', 'dependency', 'edjefe', 'edjefa'])
null_columns = train2.columns[train2.isnull().any()]
train2[null_columns].isnull().sum()
train3 = train2.drop(columns = ['v2a1', 'v18q1', 'rez_esc', 'meaneduc', 'SQBmeaned'])
ntrain = train3.dropna()
ntrain.head()
test = pd.read_csv("../input/test.csv")
null_columns = test.columns[test.isnull().any()]
test[null_columns].isnull().sum()
Xtest = test.drop(columns = ['Id', 'idhogar', 'dependency', 'edjefe', 'edjefa', 'v2a1', 'v18q1', 'rez_esc', 'meaneduc', 'SQBmeaned'])
Xntest = Xtest.dropna()
Xid = test.drop(columns = ['idhogar', 'dependency', 'edjefe', 'edjefa', 'v2a1', 'v18q1', 'rez_esc', 'meaneduc', 'SQBmeaned'])
Xnid = Xid.dropna()

Xid.shape

Xtrain = ntrain.drop(columns = ["Target"])
Ytrain = ntrain.Target
knn = KNeighborsClassifier(n_neighbors=3)
scores = cross_val_score(knn, Xtrain, Ytrain, cv=10)
np.mean(scores)
knn = KNeighborsClassifier(n_neighbors = 97)
knn.fit(Xtrain, Ytrain)
Ypred = knn.predict(Xntest)
result = np.vstack((Xid["Id"], Ypred)).T
x = ["Id","Target"]
Resultado = pd.DataFrame(columns = x, data = result)
Resultado.to_csv("results.csv", index = False)
Resultado


'''
From: https://keras.io/getting-started/sequential-model-guide/#multilayer-perceptron-mlp-for-multi-class-softmax-classification
'''
#Imports
#Initialize neural network model
import numpy as np
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization, AveragePooling2D
from keras.optimizers import SGD, Adadelta
from keras.preprocessing import image
from img_loader import load_images
import tensorflow as tf
from keras.utils import multi_gpu_model, to_categorical
from keras.models import load_model
from sklearn.model_selection import train_test_split
import os

#Custom python scripts
from prediction_chooser import get_highest_predictions
#For preprocessing images
from keras.preprocessing.image import ImageDataGenerator
from exp_stats import save_stats, save_data_info, save_histogram
from exp_stats import plot_confusion_matrix
from img_loader import load_images

# Importing augmentation functions
from augmentationsettings import augmentationSettings

#Building CNN model

def __get_image_generator(path, X_train, X_test, y_train, y_test):
    #Preprocessing images to avoid overfitting
    '''
    Performing augmentation of images.
    Preparing test data.
    Data directory name will be the label.
    '''
    # Augmentation settings from document
    train_datagen = augmentationSettings("basicAug")
    test_datagen = ImageDataGenerator(rescale=1./255)

    #Create image dirs if not exists
    train_dir = '{0}training_images'.format(path)
    test_dir = '{0}test_images'.format(path)
    if not os.path.exists(train_dir):
        os.makedirs(train_dir)
    if not os.path.exists(test_dir):
        os.makedirs(test_dir)

    train_set = train_datagen.flow(X_train, y_train,
                                   save_to_dir=train_dir,
                                   batch_size=5)
    test_set = test_datagen.flow(X_test, y_test,
                                 save_to_dir=test_dir,
                                 batch_size=5)

    return (train_datagen, test_datagen, train_set, test_set)

def __create_model():
    #Creates sequential network
    model = Sequential()

    #Convolution
    '''
    Adding convolutional layer
    param 1: number of filters
    param 2: filter shape (matrix)
    param 3: input shape 200x200 image, and type, 3 = RGB
    param 4: activation function, relu = rectifier function
    '''
    model.add(Conv2D(32, (5,5), strides=1, input_shape=(200, 200, 3), activation='relu'))
    model.add(Conv2D(32, (3,3), strides=1, input_shape=(200, 200, 3), activation='relu'))
    model.add(Conv2D(32, (3,3), strides=1, input_shape=(200, 200, 3), activation='relu'))

    #Pooling
    '''
    Reducing image size as much as possible
    Helps reducing number of nodes in the layers
    Trying to reduce complexity without loosing performance
    '''
    model.add(AveragePooling2D(pool_size=(2,2), strides=2))

    #Convolution
    model.add(Conv2D(64, (3,3), strides=1, input_shape=(100, 100, 3), activation='relu'))
    model.add(Conv2D(64, (3,3), strides=1, input_shape=(100, 100, 3), activation='relu'))

    #Pooling
    model.add(AveragePooling2D(pool_size=(2,2), strides=2))

    #Convolution
    model.add(Conv2D(128, (2,2), strides=1, input_shape=(50, 50, 3), activation='relu'))

    #Pooling
    model.add(AveragePooling2D(pool_size=(2,2), strides=2))

    #Convolution
    model.add(Conv2D(256, (3,3), strides=1, input_shape=(25, 25, 3), activation='relu'))

    #Pooling
    model.add(AveragePooling2D(pool_size=(2,2), strides=2))

    #Convolution
    model.add(Conv2D(512, (3,3), strides=1, input_shape=(13, 13, 3), activation='relu'))

    #Pooling
    model.add(AveragePooling2D(pool_size=(2,2), strides=2))

    #Convolution
    model.add(Conv2D(512, (3,3), strides=1, input_shape=(7, 7, 3), activation='relu'))

    #Pooling
    model.add(AveragePooling2D(pool_size=(2,2), strides=2))

    #Fully Connected Layer
    '''
    Make images into continous vector.
    Converting 2-D image pixel matrices to
    one dimensional vector.
    Keras can do the flattening automatically
    '''
    model.add(Flatten())
    model.add(Dense(512, activation='relu'))
    model.add(Dense(200, activation='relu'))

    #Output layer
    model.add(Dense(5, activation='softmax')) #research why softmax is used

    #Compiling CNN model

    '''
    optimizer: choosing stochastic gradient decent algorithm
    loss: choosing the loss function
    metrics: choosing the performance metric
    '''
    #sgd: Stochastic Gradient Decent
    model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])

    return model

def __train_model(save_path, train_set, test_set):
    model = __create_model()

    #Fitting data to model

    epochs = 2
    '''
    steps_per_epoch: number of training images
    epochs: Number of times the network will be trained
    on every training sample.
    validation_steps: number of test images
    '''
    history = model.fit_generator(train_set,
                        steps_per_epoch=2,
                        epochs=epochs,
                        validation_data=test_set,
                        validation_steps=2)

    print('Saving model...')
    model.save(save_path+'model.hdf5')
    save_stats(model, history, save_path)

    return model

def get_model(save_path, create):
    #Preprocess images in samples
    seed = 7
    X, y, label_map = load_images('../images/')

    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.2, random_state=seed)
    y_train_cat = to_categorical(y_train)
    y_test_cat = to_categorical(y_test)

    train_datagen, test_datagen, train_set, test_set = __get_image_generator(save_path,
    X_train, X_test, y_train_cat, y_test_cat)

    if save_path.endswith('.hdf5'):
            save_path = save_path[:-5]
    if create:
        model = __train_model(save_path, train_set, test_set)
    else:
        model = load_model(save_path+'.hdf5')

    save_data_info(train_datagen, test_datagen, train_set, test_set,
    len(X_train), len(X_test), len(label_map), save_path)

    #Evaluate model predictions
    print('Generating confusion matrix...')
    predictions = model.predict_generator(test_set, steps=2)
    y_pred = np.argmax(predictions, axis=1)
    y_true = y_test[:10]
    print(y_pred)
    print(y_true)
    plot_confusion_matrix(y_pred, y_true, label_map.values(), save_path)
    save_histogram(save_path, predictions)

    return model


import cv2

# def read_kbd_input(inputQueue):
#     print('Ready for keyboard input:')
#     while (True):
#         input_str = input()
#         inputQueue.put(input_str)
#
# def main():
#     EXIT_COMMAND = "exit"
#     inputQueue = queue.Queue()
#
#     inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
#     inputThread.start()
#
#     while (True):
#         if (inputQueue.qsize() > 0):
#             input_str = inputQueue.get()
#             print("input_str = {}".format(input_str))
#
#             if (input_str == EXIT_COMMAND):
#                 print("Exiting serial terminal.")
#                 break
#
#             Insert your code here to do whatever you want with the input_str.
        #
        # The rest of your program goes here.
        #
        # time.sleep(0.01)
    # print("End.")

# video_name = '/home/hclee/workspace/git_adev2/lane_localization/video/서하남-구리1.mp4'
video_name = '/home/hclee/workspace/git_adev2/lane_localization/video/20190110/sony1/movie/MAH08411.MP4'
# video_name = "/home/data/highway_lane/video/20190226/sony1.MAH01283.MP4"

caption_name = video_name[:-4] + '.srt'
capture = cv2.VideoCapture(video_name)

if capture.isOpened() == False:
    print('capture is not open')

fps = capture.get(cv2.CAP_PROP_FPS)

mode = 0
srt_index = 0
startframe = 0
endframe = 0
fps_count = 0
enterkey = 0
writeSubtitle = False

text = "waiting input code ('s') :: "

while True:
    if(capture.get(cv2.CAP_PROP_POS_FRAMES) == capture.get(cv2.CAP_PROP_FRAME_COUNT)):
        # capture.open("/home/hclee/workspace/git_adev2/lane_localization/video/서하남-구리1.mp4")
        # capture.open("/home/data/highway_lane/video/20190226/sony1.MAH01283.MP4")
        capture.open(video_name)

    ret, frame = capture.read()
    fps_count = fps_count + 1

    # if cv2.waitKey(33) > 0: break
    # try:
    #     number = nput("what's your name???")
    # except ValueError:
    #     print("Invalid number")

    key = cv2.waitKey(9)

    if key >= 48 and key < 57:
        if mode == 0:
            if key == 49:
                text = '000010400'
                number = '000010400'
            elif key == 50:
                text = '000020400'
                number = '000020400'
            elif key == 51:
                text = '000030400'
                number = '000030400'
            elif key == 52:
                text = '000040400'
                number = '000040400'
            elif key == 53:
                text = '100020400'
                number = '100020400'

            enterkey = key
            mode = 1
            startframe = fps_count
            srt_index = srt_index + 1
        # elif mode == 1 and enterkey == key:
        # elif mode == 1:
        #     mode = 0
        #     endframe = fps_count
        #     writeSubtitle = True
    # spacebar
    elif key == 32:
        if mode == 1:
            mode = 0
            endframe = fps_count
            writeSubtitle = True
            number = '00000000'
            text = "ready subtitle~"
        else:
            mode = 1
            startframe = fps_count
            srt_index = srt_index + 1
            text = "save subtitle~"
    elif key == ord('s'):
    # if key == ord('s'):
        try:
            number = input("enter label code :: ")
            text = number
        except ValueError:
            print("Invalid number")

        enterkey = key
        startframe = fps_count
        srt_index = srt_index + 1
    elif key == ord('e'):
        endframe = fps_count
        writeSubtitle = True
        # text = "input code ('s') :: "
    elif key == 27:
        break
    else:
        output = frame

    if writeSubtitle == True:
        startTime = '{:02d}:{:02d}:{:02d},00'.format(int((startframe / fps) // 3600), int((startframe / fps) % 3600 // 60), int((startframe / fps) % 60))
        endTime = '{:02d}:{:02d}:{:02d},00'.format(int((endframe / fps) // 3600), int((endframe / fps) % 3600 // 60), int((endframe / fps) % 60))
        srtfile = open(caption_name, mode='a', encoding='utf-8')
        str = (("%d\n%s --> %s\n%s\n\n") % (srt_index, startTime, endTime, number))
        srtfile.write(str)
        srtfile.close()
        # text = 'please input code :: '
        number = ''
        writeSubtitle = False

    # Write some Text

    font = cv2.FONT_HERSHEY_SIMPLEX
    bottomLeftCornerOfText = (10, 500)
    fontScale = 1
    fontColor = (255, 255, 255)
    lineType = 2

    cv2.putText(frame, text,
                bottomLeftCornerOfText,
                font,
                fontScale,
                fontColor,
                lineType)

    imS = cv2.resize(frame, (480, 270))
    cv2.imshow("VideoFrame", imS)

capture.release()
cv2.destroyAllWindows()