"""Test the reader object."""

from pytest_cases import parametrize_with_cases

from wingline.files import filetype, reader

@parametrize_with_cases(
    "path,content_hash,container,format,line_count", cases="tests.cases.files"
)
def test_reader(path, content_hash, container, format, line_count):
    """The reader works end-to-end."""

    reader_object = reader.Reader(path)
    assert isinstance(reader_object.container, container)
    assert reader_object.format_type is format
    with reader_object as file_reader:
        first_line = next(file_reader)
        assert first_line
        assert isinstance(first_line, dict)

@parametrize_with_cases(
    "path,content_hash,container,format,line_count", cases="tests.cases.files"
)
def test_get_reader(path, content_hash, container, format, line_count):
    """Get a reader object for the file."""

    with filetype.get_reader(path) as file_reader:
        first_line = next(file_reader)
        assert first_line
        assert isinstance(first_line, dict)


import sys
from utils.utils import *

class TSP:
    def __init__(self, graph: Graph):
        # edges of the shortest tour
        self.edges = dict()
        self.tourLength = sys.maxsize
        self.graph = graph
        self.totalTours = 0

    def solve(self, start: str):
        startNode: Node = self.graph.nodes.get(start)
        edges: dict = startNode.outflowEdges
        nodesVisited = set()
        edgesVisited = dict()
        nodesVisited.add(start)
        for name, length in edges.items():
            target = self.graph.nodes.get(name)
            nodesVisited.add(target.name)
            edge = Edge(start, name, length)
            edgesVisited[edge.getEdgeKey()] = edge
            self.travel(start, target, nodesVisited, edgesVisited)
            nodesVisited.remove(target.name)
            edgesVisited.pop(edge.getEdgeKey())
        assert len(edgesVisited) == 0
        assert len(nodesVisited) == 1

    def dumpTour(self, edges: list):
        print("[%d] tour length: %d" % (self.totalTours, self.calculateEdgesLength(edges)))
        for edge in edges:
            print(edge.srcNodeName + " --> " + edge.targetNodeName + "  :  " + str(edge.edgeLength))

    def calculateEdgesLength(self, edges: list):
        totalLength = 0
        for edge in edges:
            totalLength += edge.edgeLength
        return totalLength

    def travel(self, start: str, curNode: Node, nodesVisited: set, edgesVisited: dict):
        # if all nodes visited, then the tour is done
        # check whether the current tour is the shortest tour
        if len(nodesVisited) == len(self.graph.nodes):
            for name, length in curNode.outflowEdges.items():
                if name == start:
                    edge = Edge(curNode.name, start, length)
                    edgesVisited[edge.getEdgeKey()] = edge
                    totalLength = self.calculateEdgesLength(edgesVisited.values())
                    if totalLength < self.tourLength:
                        self.tourLength = totalLength
                        self.edges = copy.deepcopy(edgesVisited)
                    self.totalTours += 1
                    self.dumpTour(edgesVisited.values())
                    edgesVisited.pop(edge.getEdgeKey())
                    return
            assert False
            return

        edges: dict = curNode.outflowEdges
        for name, length in edges.items():
            if name in nodesVisited:
                continue
            targetNode = self.graph.nodes.get(name)
            nodesVisited.add(name)
            edge = Edge(curNode.name, name, length)
            edgesVisited[edge.getEdgeKey()] = edge
            self.travel(start, targetNode, nodesVisited, edgesVisited)
            nodesVisited.remove(targetNode.name)
            edgesVisited.pop(edge.getEdgeKey())


import os
import json
from lda import *
from flask_cors import CORS

import openai
from flask import Flask, redirect, render_template, request, url_for, jsonify

app = Flask(__name__)
CORS(app)
openai.api_key = os.getenv("OPENAI_API_KEY")

@app.route("/", methods=['POST'])
def index():
    print("received request")

    # extract url from request
    url = request.get_data().decode('utf-8')
    print(url)
    url = json.loads(url)
    url = url["url"]

    # use LDA to get top topics
    print("calling lda")
    topics_from_lda = generateTopics(url)
    print(topics_from_lda)
    print("done calling lda")

    # call openAI for summaries
    pr = generate_prompt_topics(topics_from_lda, url)
    print(pr)
    response1 = openai.Completion.create(
        model="text-davinci-003",
        prompt=pr,
        temperature=0.1,
        max_tokens=3800
    )

    # get related links by calling openAI
    pr = generate_prompt_related_links(url)
    print(pr)
    response2 = openai.Completion.create(
        model="text-davinci-003",
        prompt=pr,
        temperature=0.1,
        max_tokens=3800
    )

    response = {
        "result": response1.choices[0].text + "\n" + response2.choices[0].text

    }
    print(response)
    return jsonify(response), 200

def generate_prompt_related_links(url):
    return """Generate related links and resources list for the content in this webpage: {}
""".format(url)

def generate_prompt_topics(words, url):
    return """Generate top 5 topics (topic name as a string) from this webpage: {}, where each topic is generated from the keywords present in this list : {}. Each entry in this list contains the top words for each topic. Also generate summaries for each topic in the webpage
""".format(url, words)

def generate_prompt(link):
    return """Generate top topics in this web page along with their brief summaries: {}
""".format(link)

if __name__ == "__main__":
    print("started")
    app.run(host='0.0.0.0',port=8000)


# Create a `Stack` class that stores elements
# It should have a `size` method that returns number of elements it has
# It should have a `push` method that adds an element to the stack
# It should have a `pop` method that returns the last element form the stack and also deletes it from it

# please don`t use the built in methods

class Stack():

    def __init__(self):
        self.storage = [] # This is the list of elements.

    def push(self, item):
        self.storage += [item]
        print("Element",[item],"added")
        return self.storage

    def size(self):
        self.storage_size = len(self.storage)
        print("Stack has",self.storage_size,"elements")
        return self.storage_size

    def pop(self):
        self.lastelement = self.storage[len(self.storage)-1]
        print("Element", self.lastelement, "is to be deleted.")
        del self.storage[len(self.storage)-1]
        return self.storage

myStack = Stack()
print("Stack created")
myStack.push("Apple")
myStack.push("Apple")
myStack.push("Pen")
myStack.push("Apple")
myStack.push("Pineapple")


# selecting a Data-Structure to handle images effeciently
import numpy as np

# For handling the Folder/Files Structure
import os

# Reading images and performing Image processing
import cv2
from PIL import Image
import tensorflow as tf

# visualizing the images
from matplotlib import pyplot as plt
plt.switch_backend('Agg')

# GAN model
import tensorflow_hub as hub

# miscellaneous purpose
import math
import time
from skimage.metrics import structural_similarity as ssim

# SAVED_MODEL_PATH = "https://tfhub.dev/captain-pool/esrgan-tf2/1"
SAVED_MODEL_PATH = "esrgan-tf2_1"
model = hub.load(SAVED_MODEL_PATH)

def psnr(target, ref):
    """define a function for peak signal-to-noise ratio (PSNR)"""
    # assume RGB image
    target_data = target.astype(float)
    ref_data = ref.astype(float)

    diff = ref_data - target_data
    diff = diff.flatten('C')

    rmse = math.sqrt(np.mean(diff ** 2.))

    return 20 * math.log10(255. / rmse)

def mse(target, ref):
    """define function for mean squared error (MSE)"""
    # the MSE between the two images is the sum of the squared difference between the two images
    err = np.sum((target.astype('float') - ref.astype('float')) ** 2)
    err /= float(target.shape[0] * target.shape[1])
    return err

def compare_images(target, ref):
    """define function that combines all three image quality metrics"""
    un_changed = "Shape: "+str(target.shape)+"\n"+"D-Type: "+str(target.dtype)
    # ref = cv2.resize(ref,(target.shape[1],target.shape[0]))
    target = cv2.resize(target,(ref.shape[1],ref.shape[0]))
    return  f'PSNR: {psnr(target,ref)}\nMSE: {mse(target,ref)}\nSSIM: {ssim(target, ref, multichannel =True)}\n{un_changed}'

def image_preparation_for_model(image=None, path=None):
    ''' Function to read image and prepare it for the model
     to predict the super resolution image as an output'''
    if path:
        hr_image = cv2.imread(path)
        hr_image = cv2.cvtColor(hr_image,cv2.COLOR_BGR2RGB)
    else:
        hr_image = image

    hr_size = (np.array(hr_image.shape[:-1]) // 4) * 4

    hr_image = tf.image.crop_to_bounding_box(hr_image, 0, 0, hr_size[0], hr_size[1])
    hr_image = tf.cast(hr_image, tf.float32)
    hr_image = tf.expand_dims(hr_image, 0)

    return hr_image

def convert_to_viewable_image(nd_image):
    image_array = tf.squeeze(nd_image)
    image_array = np.clip(image_array, a_min = 0, a_max = 255)
    return image_array.astype("uint8")

def downscale_image(image):
    """
      Scales down images using bicubic downsampling.
      Args:
          image: 3D or 4D tensor of preprocessed image
    """
    image_size = []
    if len(image.shape) == 3:
        image_size = [image.shape[1], image.shape[0]]
    else:
        raise ValueError("Dimension mismatch. Can work only on single image.")

    image = tf.squeeze(tf.cast(tf.clip_by_value(image, 0, 255), tf.uint8))

    lr_image = np.asarray(Image.fromarray(image.numpy()).resize([image_size[0] // 4, image_size[1] // 4],Image.BICUBIC))
    lr_image = tf.expand_dims(lr_image, 0)
    lr_image = tf.cast(lr_image, tf.float32)
    return lr_image

def predict_normal(image_path,file_name):
    original_image = cv2.imread(image_path)
    original_image = cv2.cvtColor(original_image,cv2.COLOR_BGR2RGB)

    plt.figure(figsize=(15, 10))

    plt.subplot(1,2,1)
    plt.imshow(original_image)
    plt.title("ORIGINAL IMAGE",size=15,weight="bold")
    text = "Shape: "+str(original_image.shape)+"\n"+"D-Type: "+str(original_image.dtype)
    plt.xlabel(text,size=15,weight="bold")

    plt.subplot(1,2,2)
    processed_image = image_preparation_for_model(path=image_path)
    GAN_output = model(processed_image)
    gan_out = convert_to_viewable_image(GAN_output)
    plt.imshow(gan_out)
    plt.title("SUPER RESOLUTION IMAGE",size=15,weight="bold")
    plt.xlabel(compare_images(gan_out,original_image),size=15,weight="bold")

    plt.tight_layout()
    plt.savefig(file_name, bbox_inches="tight")
    plt.show()

def predict_degrade(image_path,file_name):
    original_image = cv2.imread(image_path)
    original_image = cv2.cvtColor(original_image,cv2.COLOR_BGR2RGB)

    plt.figure(figsize=(15, 10))

    plt.subplot(1,3,1)
    plt.imshow(original_image)
    plt.title("ORIGINAL IMAGE",size=15,weight="bold")
    text = "Shape: "+str(original_image.shape)+"\n"+"D-Type: "+str(original_image.dtype)
    plt.xlabel(text,size=15,weight="bold")
    plt.ioff()

    plt.subplot(1,3,2)
    degraded_image = downscale_image(original_image)
    d_img = convert_to_viewable_image(degraded_image)
    plt.imshow(d_img)
    plt.title("DRGRADED IMAGE",size=15,weight="bold")
    plt.xlabel(compare_images(d_img,original_image),size=15,weight="bold")
    plt.ioff()

    plt.subplot(1,3,3)
    GAN_output = model(degraded_image)
    gan_out = convert_to_viewable_image(GAN_output)
    plt.imshow(gan_out)
    plt.title("SUPER RESOLUTION IMAGE",size=15,weight="bold")
    plt.xlabel(compare_images(gan_out,original_image),size=15,weight="bold")
    plt.ioff()

    plt.tight_layout()
    plt.savefig(file_name, bbox_inches="tight")


#!/usr/bin/env python
# -*-coding:utf-8-*-

import json
import shortuuid
import base64
from websdk.jwt_token import gen_md5
from websdk.tools import check_password
from libs.base_handler import BaseHandler
from websdk.db_context import DBContext
from models.admin import UserRoles, Stakeholder, Companylist, model_to_dict
from websdk.consts import const
from websdk.cache_context import cache_conn
from websdk.tools import convert
from websdk.web_logs import ins_log
import os
import pandas as pd

def sync_stakeholder_to_redis():
    redis_conn = cache_conn()
    with DBContext('r') as session:
        dict_info = session.query(Stakeholder).all()
    for msg in dict_info:
        data_dict = model_to_dict(msg)
        tempstr = data_dict["username"]
        redis_conn.hset('stakeholder_hash', data_dict["id"], tempstr)

class StakeholderHandler(BaseHandler):
    def get(self, *args, **kwargs):
        data_list = []
        key = self.get_argument('key', default=None, strip=True)
        value = self.get_argument('value', default=None, strip=True)
        page_size = self.get_argument('page', default=1, strip=True)
        limit = self.get_argument('limit', default=30, strip=True)
        limit_start = (int(page_size) - 1) * int(limit)
        user_list = []
        with DBContext('r') as session:
            conditions = []
            if key == "username":
                conditions.append(Stakeholder.username.like('%{}%'.format(value)))
            if key == "company":
                conditions.append(Stakeholder.company.like('%{}%'.format(value)))
            if key == "department":
                conditions.append(Stakeholder.department.like('%{}%'.format(value)))
            if key == "position":
                conditions.append(Stakeholder.position.like('%{}%'.format(value)))
            if key == "duty":
                conditions.append(Stakeholder.duty.like('%{}%'.format(value)))
            if key == "tel":
                conditions.append(Stakeholder.tel.like('%{}%'.format(value)))
            if key == "addr":
                conditions.append(Stakeholder.addr.like('%{}%'.format(value)))
            if key == "email":
                conditions.append(Stakeholder.email.like('%{}%'.format(value)))
            if key == "remarks":
                conditions.append(Stakeholder.remarks.like('%{}%'.format(value)))

            todata = session.query(Stakeholder).filter(*conditions).order_by(Stakeholder.ctime.desc()).offset(
                limit_start).limit(int(limit)).all()
            tocount = session.query(Stakeholder).filter(*conditions).count()

        for msg in todata:
            case_dict = {}
            data_dict = model_to_dict(msg)
            case_dict["id"] = data_dict["id"]
            case_dict["username"] = data_dict["username"]
            case_dict["company"] = data_dict["company"]
            case_dict["department"] = data_dict["department"]
            case_dict["position"] = data_dict["position"]
            case_dict["duty"] = data_dict["duty"]
            case_dict["tel"] = data_dict["tel"]
            case_dict["addr"] = data_dict["addr"]
            case_dict["email"] = data_dict["email"]
            case_dict["remarks"] = data_dict["remarks"]

            case_dict["ctime"] = str(data_dict["ctime"])
            data_list.append(case_dict)

        if len(data_list) > 0:
            self.write(dict(code=0, msg='获取成功', count=tocount, data=data_list))
        else:
            self.write(dict(code=-1, msg='没有相关数据', count=0, data=[]))

    def post(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))
        username = data.get('username', None)
        company = data.get('company', None)
        department = data.get('department', None)
        position = data.get('position', None)
        duty = data.get('duty', None)
        tel = data.get('tel', None)
        addr = data.get('addr', None)
        email = data.get('email', None)
        remarks = data.get('remarks', None)
        if not username or not company:
            return self.write(dict(code=-1, msg='参数不能为空'))
        with DBContext('r') as session:
            user_info2 = session.query(Stakeholder).filter(Stakeholder.tel == tel).first()
            user_info3 = session.query(Stakeholder).filter(Stakeholder.email == email).first()
        # if user_info1:
        #     return self.write(dict(code=-2, msg='微信号已存在，请重新输入。'))

        if user_info2:
            return self.write(dict(code=-3, msg='手机号已存在，请重新输入。'))

        # if user_info3:
        #     return self.write(dict(code=-4, msg='邮箱已存在，请重新输入。'))

        with DBContext('w', None, True) as session:
            session.add(Stakeholder(
                username=username,
                department=department,
                company=company,
                position=position,
                duty=duty,
                tel=tel,
                addr=addr,
                email=email,
                remarks=remarks,
            ))
            session.commit()

        sync_stakeholder_to_redis()
        self.write(dict(code=0, msg='成功', count=0, data=[]))

    def delete(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))
        id = data.get('id', None)
        if not id:
            return self.write(dict(code=-1, msg='ID不能为空'))

        redis_conn = cache_conn()
        redis_conn.hdel('stakeholder_hash', id)

        with DBContext('w', None, True) as session:
            session.query(Stakeholder).filter(Stakeholder.id == id).delete(synchronize_session=False)
        self.write(dict(code=0, msg='删除成功'))

    def put(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))
        id = data.get('id', None)
        username = data.get('username', None)
        company = data.get('company', None)
        department = data.get('department', None)
        position = data.get('position', None)
        duty = data.get('duty', None)
        tel = data.get('tel', None)
        addr = data.get('addr', None)
        email = data.get('email', None)
        remarks = data.get('remarks', None)

        # if not key or not value or not user_id:
        #     return self.write(dict(code=-1, msg='不能为空'))

        try:
            with DBContext('w', None, True) as session:
                session.query(Stakeholder).filter(Stakeholder.id == id).update({
                    Stakeholder.username: username,
                    Stakeholder.company: company,
                    Stakeholder.department: department,
                    Stakeholder.position: position,
                    Stakeholder.duty: duty,
                    Stakeholder.tel: tel,
                    Stakeholder.addr: addr,
                    Stakeholder.email: email,
                    Stakeholder.remarks: remarks,
                })
                session.commit()
        except Exception as e:
            return self.write(dict(code=-2, msg='修改失败，请检查数据是否合法或者重复'))
        sync_stakeholder_to_redis()
        self.write(dict(code=0, msg='编辑成功'))

class Stakeholder_redisList(BaseHandler):
    def get(self, *args, **kwargs):
        data_list = []
        redis_conn = cache_conn()
        stakeholder_all = redis_conn.hgetall('stakeholder_hash')
        data_dict = convert(stakeholder_all)
        for k, v in data_dict.items():
            data_list.append({"k": k, "v": v})
            # ins_log.read_log('info', k)
        if len(data_list) > 0:
            self.write(dict(code=0, msg='获取成功', data=data_list))
        else:
            self.write(dict(code=-1, msg='没有相关数据', data=[]))

class StakeholderList(BaseHandler):
    def get(self, *args, **kwargs):
        data_list = []
        key = self.get_argument('key', default=None, strip=True)
        value = self.get_argument('value', default=None, strip=True)
        user_list = []
        if key == "company":
            with DBContext('r') as session:
                todata = session.query(Stakeholder).filter(Stakeholder.company == value).order_by(Stakeholder.ctime.desc()).all()
                tocount = session.query(Stakeholder).filter(Stakeholder.company == value).count()

        for msg in todata:
            case_dict = {}
            data_dict = model_to_dict(msg)
            case_dict["id"] = data_dict["id"]
            case_dict["username"] = data_dict["username"]
            case_dict["company"] = data_dict["company"]
            case_dict["department"] = data_dict["department"]
            case_dict["position"] = data_dict["position"]
            case_dict["duty"] = data_dict["duty"]
            case_dict["tel"] = data_dict["tel"]
            case_dict["addr"] = data_dict["addr"]
            case_dict["email"] = data_dict["email"]
            case_dict["remarks"] = data_dict["remarks"]
            case_dict["ctime"] = str(data_dict["ctime"])
            data_list.append(case_dict)

        if len(data_list) > 0:
            self.write(dict(code=0, msg='获取成功', count=tocount, data=data_list))
        else:
            self.write(dict(code=-1, msg='没有相关数据', count=0, data=[]))

class uploadStakeholder(BaseHandler):
    def post(self, *args, **kwargs):
        ###文件保存到本地
        Base_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        upload_path = '{}/static/stakeholder/'.format(Base_DIR)
        file_body = self.request.files["file"][0]["body"]
        file_path = upload_path + "tempfile.xls"
        with open(file_path, 'wb') as up:
            up.write(file_body)
        df = pd.read_excel(file_path)
        allsum = len(df.index)
        ins_log.read_log('info', allsum)
        for i in range(0, allsum):
            username = str(df.iloc[i, 0]),
            company = str(df.iloc[i, 1]),
            department = str(df.iloc[i, 2]),
            position = str(df.iloc[i, 3]),
            duty = str(df.iloc[i, 4]),
            tel = str(df.iloc[i, 5]),
            addr = str(df.iloc[i, 6]),
            email = str(df.iloc[i, 7]),
            remarks = str(df.iloc[i, 8]),
            with DBContext('r') as session:
                tocount = session.query(Companylist).filter(Companylist.company == company).count()
            if tocount <= 0:
                with DBContext('w', None, True) as session:
                    session.add(Companylist(
                        company=company,
                    ))
                    session.commit()
            try:
                with DBContext('w', None, True) as session:
                    session.add(Stakeholder(
                        username=username,
                        company=company,
                        department=department,
                        position=position,
                        duty=duty,
                        tel=tel,
                        addr=addr,
                        email=email,
                        remarks=remarks,
                    ))
                session.commit()
            except:
                continue
        # session.commit()
        sync_stakeholder_to_redis()

stakeholder_urls = [
    (r"/v2/accounts/stakeholder/", StakeholderHandler),
    (r"/v2/accounts/stakeholderredislist/", Stakeholder_redisList),
    (r"/v2/accounts/stakeholderlist/", StakeholderList),
    (r"/v2/accounts/stakeholder/upload/", uploadStakeholder),
]

if __name__ == "__main__":
    pass


from rest_framework.views import APIView

from dash.models import Follow
from .serializers import AuthorSerializer
from .dataUtils import validateData, getAuthor, getFriendsListData
from .verifyUtils import multiFriendQueryValidators, DependencyError
from .httpUtils import JSONResponse

class AuthorFriendsView(APIView):
    """
    This view gets a list of an author's friends.
    """
    def get(self, request, aid):
        author = getAuthor(request, aid)

        # Start data response
        data = {}
        data['query']  = 'friends'

        # Get list of friends
        urls = []
        for follow in author.follow.all():
            urls.append(follow.friend)
        data['authors'] = urls

        return JSONResponse(data)

    def post(self, request, aid):
        """
        Rather than posting a list of friends to add this is a question about
        whether or not a list of author id urls are friends with the POST'd to
        user.
        """
        # Get the author requested
        author = getAuthor(request, aid)

        # Get the data from the POST
        data = getFriendsListData(request)
        validateData(data, multiFriendQueryValidators)

        # Ensure that they POST'd to the url they said they were POSTing to
        if author.id != data['author']:
            data = {'author.id': author.id,
                    'query.author': data['author']}
            raise DependencyError(data)

        # Get all follows for the author ONCE. Filter later.
        authorFollows = Follow.objects.filter(author=author)

        # This is the list of people we consider friends from the list they sent
        ourFriends = []

        for friendId in data['authors']:
            try:
                # We don't actually care what we get back, if it doesn't throw
                # an exception then we're friends
                authorFollows.get(friend=friendId)
                ourFriends.append(friendId)
            except Follow.DoesNotExist:
                # If there's an exception we don't care, just move on
                pass

        # Our return data
        rv = {
            'query': 'friends',
            'author': author.id,
            'friends': ourFriends
        }

        return JSONResponse(rv)

class AuthorIsFriendsView(APIView):
    """
    This view gets whether or not this user is friends with another.
    """
    def get(self, request, aid=None, other=None):
        """
        This checks if the author at aid is friends with the author that has aid
        than other.
        """
        author = getAuthor(request, aid)

        # Make http id, and https id for back up
        otherId = 'http://' + other
        otherIdHttps = 'https://' + other

        # Get the following relationship
        follows = Follow.objects.filter(author=author, friend=otherId)

        # If we didn't find one then try with https
        if len(follows) == 0:
            follows = Follow.objects.filter(author=author, friend=otherIdHttps)

        # Start data return
        data = {}
        data['query'] = 'friends'

        # If we didn't find something this time then they're definitely not
        # friends as far as we can tell
        if len(follows) == 0:
            data['authors'] = [author.id, otherId]
            data['friends'] = False
        else:
            follow = follows[0]
            data['authors'] = [author.id, follow.friend]
            data['friends'] = True

        return JSONResponse(data)


from flask import Flask, request, send_file
from flask_cors import CORS

from gopro_client import GoProClient
from image_cache import ImageCache
from calibration import Calibrator
from environment import Environment
from resetter import Reset

app = Flask(__name__)
CORS(app)

# gpCam.downloadLastMedia(gpCam.shoot_video(i), custom_filename="VIDEO_"+str(i)+".MP4")

@app.route('/')
def hello_world():
	return 'Hello World!'

@app.route('/video/')
def video():
	return {
		'success': False,
		'message': 'Video not supported yet'
	}

@app.route('/status/')
def status():
	return {
		'success': True,
		'message': '',
		'connected': False
	}

@app.route('/image/')
def get_image():
	image_cache = ImageCache.get_instance()
	image_id = int(request.args.get('id'))
	try:
		image_info = image_cache.get_image(image_id)
		image_path = image_info.path
	except:
		print('unable to load image', image_id)
		image_path = Environment.get_default_image_path()
	return send_file(image_path, mimetype='image/png')

@app.route('/snapshots/', methods=['GET', 'PUT', 'DELETE'])
def snapshots():
	image_cache = ImageCache.get_instance()
	if request.method == 'GET':
		return {
			'success': True,
			'message': 'retrieved current snapshots',
			'snapshots': [
				info.to_json()
				for info in image_cache.get_snapshots()
			]
		}
	elif request.method == 'PUT':
		gopro = GoProClient.get_instance()
		photo = gopro.take_photo()
		info = image_cache.add_snapshot(photo)
		return {
			'success': True,
			'message': '',
			'image-info': info.to_json()
		}
	elif request.method == 'DELETE':
		image_cache.remove_image(request.json['id'])
		return {
			'success': True,
			'message': 'removed the snapshot'
		}

@app.route('/reset/', methods=['GET', 'PUT', 'DELETE'])
def reset():
	reset = Reset.get_instance()
	# status = GoProClient.get_instance().status()
	if request.method == 'GET':
		image_cache = ImageCache.get_instance()
		info = image_cache.current_reset_image
		if info is None:
			return {
				'success': False,
				'message': 'currently no image'
			}
		return {
			'success': True,
			'message': '',
			'image': info.to_json()
		}
	elif request.method == 'PUT':
		reset = Reset.get_instance()
		if reset.resetting:
			return {
				'success': True,
				'message': 'already resetting'
			}
		reset.begin_reset()
		return {
			'success': True,
			'message': 'started resetting'
		}
	elif request.method == 'DELETE':
		if not reset.resetting:
			return {
				'success': True,
				'message': 'not currently resetting'
			}
		reset.end_reset()
		return {
			'success': True,
			'message': 'stopped resetting'
		}

@app.route('/calibration/', methods=['GET', 'PUT'])
def calibration():
	a = ImageCache.get_instance()
	if request.method == 'GET':
		# return the current calibration image
		pass
	elif request.method == 'PUT':
		c = Calibrator.get_instance()
		c.calibrate()

if __name__ == '__main__':
	app.run()


Test.Summary = '''
Test conf_remap using a yaml file.
'''

Test.ContinueOnFail = True

class conf_remap_yaml_load_test:
    """Test conf_remap using a yaml file."""

    client_counter: int = 0
    ts_counter: int = 0
    server_counter: int = 0

    def __init__(self, name: str, gold_file="", remap_filename="", remap_content=""):
        """Initialize the test.
        :param name: The name of the test.
        :param gold_file: Gold file to be checked.
        :param remap_filename: Remap yaml filename.
        :param remap_content: remap yaml file content.
        """
        self.name = name
        self.gold_file = gold_file
        self._remap_filename = remap_filename
        self._remap_content = remap_content

    def _configure_server(self, tr: 'TestRun'):
        """Configure the server.

        :param tr: The TestRun object to associate the server process with.
        """
        server = Test.MakeOriginServer(f"server-{conf_remap_yaml_load_test.ts_counter}", lookup_key="{%Host}{PATH}")
        request_header2 = {
            "headers": "GET /test HTTP/1.1\r\nHost: www.testexample.com\r\n\r\n",
            "timestamp": "1469733493.993",
            "body": ""
        }
        response_header2 = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}

        server.addResponse("sessionfile.log", request_header2, response_header2)
        conf_remap_yaml_load_test.server_counter += 1
        self._server = server

    def _configure_traffic_server(self, tr: 'TestRun'):
        """Configure Traffic Server.

        :param tr: The TestRun object to associate the ts process with.
        """
        ts = Test.MakeATSProcess(f"ts-{conf_remap_yaml_load_test.ts_counter}")

        conf_remap_yaml_load_test.ts_counter += 1
        ts.Disk.records_config.update(
            '''
            diags:
                debug:
                    enabled: 1
                    tags: conf_remap
            dns:
                resolv_conf: NULL
            http:
                referer_filter: 1
            url_remap:
                pristine_host_hdr: 0 # make sure is 0

        ''')
        self._ts = ts

    def run(self, diags_fail_exp="", ts_retcode=0):
        """Run the test.
        :param diags_fail_exp: Text to be included to validate the error.
        :param ts_retcode: Expected return code from TS.
        """
        tr = Test.AddTestRun(self.name)
        self._configure_server(tr)
        self._configure_traffic_server(tr)

        tr.Processes.Default.StartBefore(self._server)
        tr.Processes.Default.StartBefore(self._ts)

        self._ts.ReturnCode = ts_retcode

        if ts_retcode > 0:  # we could have errors logged and yet, we still want to move on.
            self._ts.Ready = 0

        if diags_fail_exp != "":
            # some error logs will be written to the diags.
            self._ts.Disk.diags_log.Content = Testers.IncludesExpression(diags_fail_exp, "Have a look.")
        else:
            tr.Processes.Default.ReturnCode = 0

        if self.gold_file:
            tr.Processes.Default.Streams.stderr = self.gold_file

        if self._remap_filename != "" and self._remap_content != "":
            self._ts.Disk.MakeConfigFile(self._remap_filename).update(self._remap_content)
            self._ts.Disk.remap_config.AddLine(
                f'map http://www.testexample.com/ http://127.0.0.1:{self._server.Variables.Port} @plugin=conf_remap.so @pparam={self._remap_filename}'
            )

        tr.Processes.Default.Command = 'curl --proxy 127.0.0.1:{0} "http://www.testexample.com/test" -H "Host: www.testexample.com" --verbose'.format(
            self._ts.Variables.port)
        conf_remap_yaml_load_test.client_counter += 1

test0 = conf_remap_yaml_load_test(
    "Test success",
    gold_file="gold/200OK_test.gold",
    remap_filename="testexample_remap.yaml",
    remap_content='''
    ts:
      url_remap:
        pristine_host_hdr: 1
    ''')
test0.run()

test1 = conf_remap_yaml_load_test(
    "Test mismatch type",
    remap_filename="mismatch_field_type_remap.yaml",
    remap_content='''
    ts:
      url_remap:
        pristine_host_hdr: !!float '1'
    ''')
test1.run(diags_fail_exp="'proxy.config.url_remap.pristine_host_hdr' variable type mismatch", ts_retcode=33)

test2 = conf_remap_yaml_load_test(
    "Test invalid variable",
    remap_filename="invalid1_field_type_remap.yaml",
    remap_content='''
    ts:
      plugin:
        dynamic_reload_mode: 1
    ''')

test2.run(
    diags_fail_exp="'proxy.config.plugin.dynamic_reload_mode' is not a configuration variable or cannot be overridden",
    ts_retcode=33)

# We let the conf_remap parse two fields, only one is valid, we expect ATS to start and the invalid fields ignored.
test3 = conf_remap_yaml_load_test(
    "Test success",
    gold_file="gold/200OK_test.gold",
    remap_filename="testexample2_remap.yaml",
    remap_content='''
    ts:
      plugin:
        dynamic_reload_mode: 1

      url_remap:
        pristine_host_hdr: 1
    ''')
test3.run(diags_fail_exp="'proxy.config.plugin.dynamic_reload_mode' is not a configuration variable or cannot be overridden")

# Check null values
test4 = conf_remap_yaml_load_test(
    "Test success - with NULL variable",
    gold_file="gold/200OK_test.gold",
    remap_filename="testexample_remap.yaml",
    remap_content='''
    ts:
      url_remap:
        pristine_host_hdr: 1
      hostdb:
        ip_resolve: "NULL" # We want to make sure this gets read as it should. "NULL" could be the value of this field.
    ''')
test4.run()


"""Extract mirror subjects from 20 Questions mirror subject HITs.

See ``python extractmirrorsubjects.py --help`` for more information.
"""

import ast
import collections
import json
import logging
import re

import click

from scripts import _utils

logger = logging.getLogger(__name__)

# constants

KEY_SCHEMA = {
    'subject': str,
    'question': str,
    'answer': str,
    'quality_labels': ast.literal_eval,  # List[str]
    'score': int,
    'high_quality': bool,
    'labels': ast.literal_eval,  # List[str]
    'is_bad': bool,
    'true_votes': int,
    'majority': ast.literal_eval
}

# main function

@click.command(
    context_settings={
        'help_option_names': ['-h', '--help']
        })
@click.argument(
    'xml_dir',
    type=click.Path(exists=True, file_okay=False, dir_okay=True))
@click.argument(
    'output_path',
    type=click.Path(exists=False, file_okay=True, dir_okay=False))
def extractmirrorsubjects(xml_dir, output_path):
    """Extract mirror subjects from XML_DIR and write to OUTPUT_PATH.

    Extract mirror subject data from a batch of the mirror subjects
    HITs. XML_DIR should be an XML directory extracted with AMTI.
    OUTPUT_PATH is the location to which the data will be written in
    JSON Lines format.
    """
    # submissions : the form data submitted from the
    # mirror-subjects HITs as a list of dictionaries mapping the
    # question identifiers to the free text, i.e.:
    #
    #     [
    #       {
    #         'attribute-idx': attribute_value,
    #         ...
    #       },
    #       ...
    #     ]
    #
    # See the data for individual attributes and values. The index (idx)
    # is used because each HIT had the worker label multiple instances
    # for efficiency purposes.
    submissions = _utils.extract_xml_dir(xml_dir)

    # decode the data from the ``"attribute-idx": value`` style to the
    # individual rows.
    rows = _utils.decode_attribute_idx_data(submissions)

    # coerce the data types correctly and add in the new attribute.
    new_subjects_skipped = 0
    new_row_strs = []
    for row in rows:
        # create the new row

        # use an OrderedDict so that the keys appear in the right order
        # in the JSON.
        new_row = collections.OrderedDict([
            (attribute, as_type(row[attribute]))
            for attribute, as_type
            in KEY_SCHEMA.items()
        ])

        # clean up the raw text of the new subject
        # strip whitespace and lowercase
        new_subject = row['new_subject']\
            .strip()\
            .lower()
        # remove beginning and ending punctuation
        normalized_new_subject = re.sub(
            r'(^[^a-z0-9]|[^a-z0-9]$)',
            '',
            new_subject)

        # filter out bad examples using a few rules
        unexpected_format = not re.match(
            r'^[a-z0-9-]+$', normalized_new_subject)
        too_long = len(normalized_new_subject) > 20
        if unexpected_format or too_long:
            logger.warning(
                f'Skipping new subject "{normalized_new_subject}".')
            new_subjects_skipped += 1
            continue

        if normalized_new_subject != new_subject:
            logger.warning(
                f'New subject {new_subject} was modified to'
                f' {normalized_new_subject}.')

        new_row['subject'] = normalized_new_subject
        new_row['answer'] = None

        # delete the irrelevant label attributes since they don't apply
        # to the new subject
        del new_row['labels']
        del new_row['is_bad']
        del new_row['true_votes']
        del new_row['majority']

        new_row_strs.append(json.dumps(new_row))

    if new_subjects_skipped > 0:
        logger.warning(
            f'{new_subjects_skipped} new subjects were skipped.')

    # write out the data
    with click.open_file(output_path, 'w') as output_file:
        output_file.write('\n'.join(sorted(new_row_strs)))

if __name__ == '__main__':
    extractmirrorsubjects()


import sys
import random
from PySide6 import QtCore, QtWidgets, QtGui
import maya.cmds as cmds

class MyWidget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.cube = cmds.polyCube( sx=5, sy=5, sz=5 )
        self.sphere = cmds.polySphere(sx=10, sy=15, r=20)
        self.cone = cmds.polyCone( sx=10, sy=15, sz=5, r=20, h=10)
        self.cylinder = cmds.polyCylinder( sx=10, sy=15, sz=5, h=20)
        self.torus = cmds.polyTorus( sx=8, sy=16, r=10, sr=1 )

        self.model = [self.cube, self.sphere, self.cone, self.cylinder, self.torus]

        self.button = QtWidgets.QPushButton("Create Rando Polygon!")

        self.layout = QtWidgets.QVBoxLayout(self)
        self.layout.addWidget(self.button)

        self.button.clicked.connect(self.createPoly)

    @QtCore.Slot()
    def createPoly(self):
        self.random.choice(self.model)

if __name__ == "__main__":
    app = QtWidgets.QApplication([])

    widget = MyWidget()
    widget.resize(800, 600)
    widget.show()

    sys.exit(app.exec())


# Imports the Google Cloud client library
from google.cloud import vision
import io
import os
from recognise_ingredients.image_processing import *

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/Users/jakub/git/fraidge-ai/fraidge-fcf90a851481.json"

RELATIVE_PATH = 'images/fridge.jpg'
SHOW = False

# Load an instance of the image annotator
client = vision.ImageAnnotatorClient()

def printObj(object_):
    print('\n{} (confidence: {})'.format(object_.name, object_.score))

def loadContent(file_name):
    # Loads the image into memory
    with io.open(file_name, 'rb') as image_file:
        content = image_file.read()
    return content

def objectLocalization(file_name, factor, show=False):
    content = loadContent(file_name)
    image = vision.Image(content=content)

    objects = client.object_localization(
        image=image).localized_object_annotations

    print('Number of objects found: {}'.format(len(objects)))
    result = []
    for object_ in objects:
        # Crop object
        buffer_value = cropToBuffer(file_name, object_, factor, show)
        buffer_image = vision.Image(content=buffer_value)

        object_recognition = client.object_localization(
            image=buffer_image).localized_object_annotations
        for i in range(min(3, len(object_recognition))):
            result.append(object_recognition[i].name)
        # result.append(object_.name)
    return set(result)

def filterIngredients(set):
    removables = {
        'Food',
        'Container',
        'Animal',
        'Clock',
        'Fruit',
        'Person'
    }

    return set.difference(removables)

def main():
    file_name = os.path.abspath(RELATIVE_PATH)
    objects = objectLocalization(file_name, 0.02, show=SHOW)
    # Filter ingredients
    ingredients = filterIngredients(objects)
    print(ingredients)

if __name__ == "__main__":
    main()


import os
import shutil
import v4l2capture
from ctypes import *
import struct
import array
from fcntl import ioctl
import cv2
import numpy as np
import time
from sys import argv
import getopt
import sys
import select
import termios
import tty
import threading
import paddlemobile as pm
from paddlelite import *
import codecs
import multiprocessing
import math
import functools
from PIL import Image
from PIL import ImageFile
from PIL import ImageDraw

ImageFile.LOAD_TRUNCATED_IMAGES = True

class Car:
    def __init__(self):
        # load config
        self.config()

        # create folders
        if not os.path.exists(self.img_save_path):
            os.makedirs(self.img_save_path)
        if not os.path.exists(self.data_collect_path):
            os.makedirs(self.data_collect_path)
        img_collect_path = os.path.join(self.data_collect_path, 'img')
        if not os.path.exists(img_collect_path):
            os.makedirs(img_collect_path)

        # Initialize the camera
        camera = "/dev/video2"
        video = v4l2capture.Video_device(camera)
        video.set_format(424, 240, fourcc='MJPG')
        video.create_buffers(1)
        video.queue_all_buffers()
        video.start()
        self.video = video

        # Initialize the predictor
        self.angle_predictor = self.load_angle_model()
        self.angle_right_predictor = self.load_angle_model_right()
        self.label_predictor = self.load_label_model()

        # Initialize the lower machine
        path = os.path.split(os.path.realpath(__file__))[0] + "/.."
        lib_path = path + "/lib" + "/libart_driver.so"
        so = cdll.LoadLibrary
        self.lib = so(lib_path)
        car = "/dev/ttyUSB0"
        self.lib.art_racecar_init(38400, car.encode("utf-8"))

    def clean_predict_img(self):
        filepath = self.img_save_path
        if os.path.exists(filepath):
            shutil.rmtree(filepath)
        os.makedirs(filepath)

    def clean_data_collect(self):
        filepath = self.data_collect_path
        if os.path.exists(filepath):
            shutil.rmtree(filepath)
        os.makedirs(filepath)
        os.makedirs(filepath + '/img')

    def getvalue(self):
        axis_states = {}
        button_states = {}

        axis_map = []
        button_map = []

        buf = array.array('u', str(['\0'] * 5))
        ioctl(self.jsdev, 0x80006a13 + (0x10000 * len(buf)), buf)
        js_name = buf.tostring()

        # get number of axes and buttons
        buf = array.array('B', [0])
        ioctl(self.jsdev, 0x80016a11, buf)  # JSIOCGAXES
        num_axes = buf[0]

        buf = array.array('B', [0])
        ioctl(self.jsdev, 0x80016a12, buf)  # JSIOCGBUTTONS
        num_buttons = buf[0]

        # Get the axis map
        buf = array.array('B', [0] * 0x40)
        ioctl(self.jsdev, 0x80406a32, buf)  # JSIOCGAXMAP
        for axis in buf[:num_axes]:
            axis_name = self.axis_names.get(axis, 'unknow(0x%02x)' % axis)
            axis_map.append(axis_name)
            axis_states[axis_name] = 0.0

        # Get the button map.
        buf = array.array('H', [0] * 200)
        ioctl(self.jsdev, 0x80406a34, buf)  # JSIOCGBTNMAP

        for btn in buf[:num_buttons]:
            btn_name = self.button_names.get(btn, 'unknown(0x%03x)' % btn)
            button_map.append(btn_name)
            button_states[btn_name] = 0

        return axis_map, axis_states, button_map, button_states

    def config(self):
        # load config, modifiable
        #   Where angle_model is stored
        self.angle_model_path = '../model/angle_model/model_infer'
        self.angle_model_right_path = '../model/angle_model_right/model_infer'
        #   Where label_model is stored
        self.label_model_path = '../model/freeze_model'
        #   Where images are saved
        self.img_save_path = '../predict_img'
        #   Where the collected data is saved
        self.data_collect_path = '../data_collect'
        #   The speed at which the car runs
        self.init_vels = 1600
        #   avoiding para
        self.contiune_angle = 1500
        self.count = 0
        #   The corresponding serial number and label
        # self.label_dict = {
        #     0: 'green_light',
        #     1: 'limit',
        #     2: 'limit_end',
        #     3: 'outer',
        #     4: 'red_light',
        #     5: 'stop',
        #     6: 'straight',
        #     7: 'turn_left'
        # }
        self.label_dict = {
            # 0: 'guide'
            0:  'avoiding',
            1:	'limit',
            2:	'limit_end',
            3:	'outer',#unused
            4:	'overtake',
            5:	'red_line',#used to be stop
            6:	'stop',#unused
            7:	'back',
            8:	'straight',#used to be side_walk
            9:	'turn_left',
        }
        #   The sequence number required to save the image
        self.ImgInd = 0
        #   Flags for marker detection
        self.stop_flag = False
        self.run_flag = True
        self.limit_flag = False
        self.turn_left_flag = False
        self.P_flag = False
        self.PR_flag = False
        self.back_flag = False
        self.label = 'none'
        self.overtake_flag = True
        self.right_flag = False

    def dataset(self, video):
        lower_hsv = np.array([26, 85, 75])
        upper_hsv = np.array([34, 255, 255])

        select.select((video,), (), ())
        image_data = video.read_and_queue()
        frame = cv2.imdecode(np.frombuffer(
            image_data, dtype=np.uint8), cv2.IMREAD_COLOR)
        img_save = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        mask = cv2.inRange(hsv, lowerb=lower_hsv, upperb=upper_hsv)
        img_angle = Image.fromarray(mask)
        img_angle = img_angle.resize((128, 128), Image.ANTIALIAS)
        img_angle = np.array(img_angle).astype(np.float32)
        img_angle = cv2.cvtColor(img_angle, cv2.COLOR_GRAY2BGR)
        img_angle = img_angle / 255.0
        img_angle = np.expand_dims(img_angle, axis=0)

        img_label = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
        img_label = Image.fromarray(img_label)
        return img_label, img_angle, img_save, mask

    def load_angle_model(self):
        valid_places = (
            Place(TargetType.kFPGA, PrecisionType.kFP16, DataLayoutType.kNHWC),
            Place(TargetType.kHost, PrecisionType.kFloat),
            Place(TargetType.kARM, PrecisionType.kFloat),
        )
        config = CxxConfig()
        model_dir = self.angle_model_path
        config.set_model_file(model_dir + "/model")
        config.set_param_file(model_dir + "/params")
        config.set_valid_places(valid_places)
        predictor = CreatePaddlePredictor(config)
        return predictor

    def load_angle_model_right(self):
        valid_places = (
            Place(TargetType.kFPGA, PrecisionType.kFP16, DataLayoutType.kNHWC),
            Place(TargetType.kHost, PrecisionType.kFloat),
            Place(TargetType.kARM, PrecisionType.kFloat),
        )
        config = CxxConfig()
        model_dir_right = self.angle_model_right_path
        config.set_model_file(model_dir_right + "/model")
        config.set_param_file(model_dir_right + "/params")
        config.set_valid_places(valid_places)
        predictor = CreatePaddlePredictor(config)
        return predictor

    def load_label_model(self):
        model_dir = self.label_model_path
        pm_config = pm.PaddleMobileConfig()
        pm_config.precision = pm.PaddleMobileConfig.Precision.FP32
        pm_config.device = pm.PaddleMobileConfig.Device.kFPGA
        pm_config.model_dir = model_dir
        pm_config.thread_num = 4
        label_predictor = pm.CreatePaddlePredictor(pm_config)

        return label_predictor

    def tensor_deal(self, origin):
        tensor_img = origin.resize((256, 256), Image.BILINEAR)
        if tensor_img.mode != 'RGB':
            tensor_img = tensor_img.convert('RGB')
        tensor_img = np.array(tensor_img).astype(
            'float32').transpose((2, 0, 1))
        tensor_img -= 127.5
        tensor_img *= 0.007843
        tensor_img = tensor_img[np.newaxis, :]
        tensor = pm.PaddleTensor()
        tensor.dtype = pm.PaddleDType.FLOAT32
        tensor.shape = (1, 3, 256, 256)
        tensor.data = pm.PaddleBuf(tensor_img)
        paddle_data_feeds = [tensor]
        return paddle_data_feeds

    def angle_predict(self, predictor, image):
        tmp = np.zeros((1, 128, 128, 3))
        img = image

        i = predictor.get_input(0)
        i.resize((1, 3, 128, 128))
        tmp[0, 0:img.shape[1], 0:img.shape[2] + 0, 0:img.shape[3]] = img
        tmp = tmp.reshape(1, 3, 128, 128)
        frame = cv2.imdecode(np.frombuffer(
            img, dtype=np.uint8), cv2.IMREAD_COLOR)
        i.set_data(tmp)

        predictor.run()
        out = predictor.get_output(0)
        score = out.data()[0][0]
        return score

    def get_img_para(self, label_outputs):
        # If the score > 0.6 then the object is detected successfully
        mask = label_outputs[:, 1] > 0.5 if len(label_outputs.shape) > 1 else 0
        if np.sum(mask) > 0:
            detect = True
            labels = label_outputs[mask, 0].astype('int32')
            scores = label_outputs[mask, 1].astype('float32')
            boxes = label_outputs[mask, 2:].astype('float32')

        # No objects were detected
        else:
            detect = False
            labels = None
            scores = None
            boxes = None

        return detect, labels, scores, boxes

    def img_save(self, img, detect, boxes, labels, scores):
        img = Image.fromarray(img)

        # # Detect object, draw a rectangle around the picture
        # if detect == True:
        #     # draw = ImageDraw.Draw(img)
        #     for box, label, score in zip(boxes, labels, scores):
        #         xmin, ymin, xmax, ymax = box[0], box[1], box[2], box[3]
        #         xmin, xmax = (int(x / 608 * 320) for x in [xmin, xmax])
        #         ymin, ymax = (int(y / 608 * 240) for y in [ymin, ymax])
        #
        #         draw.rectangle((xmin, ymin, xmax, ymax), None, 'red')
        #         box_str = str(xmin) + ' ' + str(ymin) + ' ' + str(xmax) + ' ' + str(ymax)
        #         draw.text((xmin, ymin), self.label_dict[int(label)] + ' ' + str(score) + '\n' + box_str, (255, 255, 0))

        # save image
        output_path = os.path.join(
            self.img_save_path, str(self.ImgInd) + '.jpg')
        img.save(output_path)
        self.ImgInd += 1

    def user_cmd(self, detect, label_ids, scores, boxes, vel, angle, a):
        # identify
        if detect:
            for label_id, box in zip(label_ids, boxes):
                # deal box
                xmin, ymin, xmax, ymax = box[0], box[1], box[2], box[3]
                xmin, xmax = (int(x / 608 * 320) for x in [xmin, xmax])
                ymin, ymax = (int(y / 608 * 240) for y in [ymin, ymax])
                center_y = int((ymin + ymax) / 2)
                label = self.label_dict[label_id]
                print('label: ' + label)
                # if center_y > 160:
                #     print('label = ' + label)
                if label == 'stop':
                    if center_y > 60:
                        print('label = ' + label)
                        self.lib.send_cmd(1500, 1500)
                        self.run_flag = False
                if label == 'red_light':
                    if center_y > 35:
                        print('label =' + label)
                        self.lib.send_cmd(1500, 1500)

                        self.stop_flag = True
                if label == 'green_light':
                    if center_y > 25:
                        print('label = ' + label)
                        self.stop_flag = False
                if label == 'limit':
                    if center_y > 120:
                        print('label = ' + label)
                        self.limit_flag = True
                if label == 'limit_end':
                    #                    if 120<center_y <200:
                    #                        self.lib.send_cmd(15,2100)
                    if center_y > 200:
                        print(center_y)
                        print('label = ' + label)
                        self.lib.send_cmd(1528, 1760)
                        time.sleep(0.4)
                        self.lib.send_cmd(1528, 1550)
                        time.sleep(0.1)
                        self.limit_flag = False
                        self.P_flag = True
                        # self.lib.send_cmd(vel, 2000)

                if label == 'turn_left':
                    if center_y > 150:
                        print('label = ' + label)
                        # self.std_time = time.time()
                        self.turn_left_flag = True
                        self.P_flag = False
                        self.PR_flag = False
                if label == 'straight':
                    if center_y > 160:
                        print('label = ' + label)
                        self.PR_flag = True

                        self.PT_flag = True
                        pass

        # operation
        if self.stop_flag:
            self.lib.send_cmd(1500, 1500)
            return

        if self.turn_left_flag:
            time.sleep(0.6)
            self.lib.send_cmd(vel, 2250)
            time.sleep(0.3)
            self.turn_left_flag = False
            # nowtime = time.time()
            # if nowtime - self.std_time > 1.2:
            #     self.lib.send_cmd(vel, angle)
            #     self.turn_left_flag = False
            #     return
            # if nowtime - self.std_time < 0.68:
            #     self.lib.send_cmd(vel, angle)
            #     return
            #     self.lib.send_cmd(vel, 2100)
            return

        if self.limit_flag:
            # Test: unfinished
            print('limited speed')
            #            angle = int(-2174 * a * a + 3805 * a + 141.3)
            #            angle = int(-2083 * a * a + 3695* a +151.4)
            #            angle = int(-1768* a * a +3398 * a + 177.9)
            angle = int(-1792 * a * a + 3413 * a + 176.7 + 2 )
            print(angle)
            self.lib.send_cmd(1528, angle)
            return

        if self.P_flag & self.PR_flag:
            vel = 1600
            if self.PT_flag:
                self.lib.send_cmd(1600, 915)
                time.sleep(0.1)
                self.PT_flag = False

            #            angle = int(-3132*a*a*a+5114*a*a-522.2*a+874.4+30+20)
            angle = int(-2635 * a * a * a + 4710 *
                        a * a - 528.6 * a + 921.3 - 80)
            #            a= int(-2635*angle*angle*angle+4710*angle*angle-528.6*angle+921.3-38)  #test  4  8.27  右转
            print("  turn  right")

        # normal situation
        print('angle = ' + str(angle))
        self.lib.send_cmd(vel, angle)
        return

    def follow(self, detect, label_ids, scores, boxes, vel):
        if detect:
            for score in scores:
                if score > 0.1:
                    self.count = 0
                    for label_id, box in zip(label_ids, boxes):
                        # deal box
                        xmin, ymin, xmax, ymax = box[0], box[1], box[2], box[3]
                        xmin, xmax = (int(x / 608 * 320) for x in [xmin, xmax])
                        ymin, ymax = (int(y / 608 * 240) for y in [ymin, ymax])
                        center_x = int((xmin + xmax) / 2)
                        center_y = int((ymin + ymax) / 2)
                        label = self.label_dict[label_id]
                        print(label_id)
                        print('label: ' + label)
                        if label == 'guide':
                            print(center_x, center_y)
                            if center_y < 70:
                                if center_x < 100:
                                    print('left fastly')
                                    self.lib.send_cmd(1600, 1900)
                                    self.contiune_angle = 1900
                                elif 100 < center_x & center_x < 200:
                                    print('straight fastly')
                                    self.lib.send_cmd(1600, 1500)
                                elif center_x > 200:
                                    print('right fastly')
                                    self.lib.send_cmd(1600, 1100)
                                    self.contiune_angle = 1100
                            else:
                                if center_x < 100:
                                    print('left')
                                    self.lib.send_cmd(1535, 1900)
                                    self.contiune_angle = 1900
                                elif 100 < center_x & center_x < 200:
                                    print('straight')
                                    self.lib.send_cmd(1535, 1500)
                                elif center_x > 200:
                                    print('right')
                                    self.lib.send_cmd(1535, 1100)
                                    self.contiune_angle = 1100
        else:
            self.count += 1
            if self.count > 3:
                self.lib.send_cmd(1500, 1500)
                print('no guide in the carema!')
            else:
                self.lib.send_cmd(1560, self.contiune_angle)

    def avoiding(self, detect, label_ids, scores, boxes, vel, angle, mask):
        if detect:
            print(scores)
            for label_id, box in zip(label_ids, boxes):
                xmin, ymin, xmax, ymax = box[0], box[1], box[2], box[3]
                xmin, xmax = (int(x / 608 * 320) for x in [xmin, xmax])
                ymin, ymax = (int(y / 608 * 240) for y in [ymin, ymax])
                center_x = int((xmin + xmax) / 2)
                center_y = int((ymin + ymax) / 2)
                label = self.label_dict[label_id]
                right_x = 320
                left_x = 0
                print(center_x, center_y)
#                if angle < 1000:
#                    self.lib.send_cmd(1535, 500)
#                    return
                if center_y > 80:
                    for j in range(0,center_x):
                        if mask[center_y][j] == 255 and mask[center_y][j+1] == 0 and mask[center_y][j-1] == 255:
                            print('j = '+ str(j))
                            if left_x < j:
                                left_x = j
                    for i in range(center_x,319):
                        if mask[center_y][i] == 255 and mask[center_y][i+1] == 255 and mask[center_y][i-1] ==0:
                            print('i ='+str(i))
                            if right_x > i:
                                right_x = i
#				print('right_x ='+str(right_x))
#				print('left_x ='+str(left_x))
                    distance_left = center_x - left_x
                    distance_right = right_x - center_x
#				print('distance_left ='+str(distance_left))
#				print('distance_right ='+str(distance_right))
                    if distance_right > distance_left:
                        print('turn right')
                        self.lib.send_cmd(1560,500)
                    else:
                        print('turn left')
                        self.lib.send_cmd(1560,2300)
                else:
                    self.lib.send_cmd(self.init_vels, angle)

        else:
            self.lib.send_cmd(self.init_vels, angle)

    def back(self, detect, label_ids, scores, boxes, vel, angle, mask):

        if detect:
            for label_id, box in zip(label_ids, boxes):
                xmin, ymin, xmax, ymax = box[0], box[1], box[2], box[3]
                xmin, xmax = (int(x / 608 * 320) for x in [xmin, xmax])
                ymin, ymax = (int(y / 608 * 240) for y in [ymin, ymax])
                center_x = int((xmin + xmax) / 2)
                center_y = int((ymin + ymax) / 2)
                label = self.label_dict[label_id]
                if center_y > 130:
                    print('label = ' + self.label)
                    self.back_flag = True
                else:
                    self.lib.send_cmd(1560, angle)
                if self.back_flag :
                    print('backing')
                    # self.lib.send_cmd(500, 1500)
                    # time.sleep(0.1)
                    # self.lib.send_cmd(1440, 1010)
                    # time.sleep(1.8)
                    # self.lib.send_cmd(500, 1500)
                    # time.sleep(0.1)
                    # print('the program is dead')
                    # while True:
                    #     self.lib.send_cmd(1500, 1500)
                    for j in range(0,center_x):
                        if mask[center_y][j] == 255 and mask[center_y][j+1] == 0 and mask[center_y][j-1] == 255:
                            print('j = '+ str(j))
                            if left_x < j:
                                left_x = j
                    for i in range(center_x,319):
                        if mask[center_y][i] == 255 and mask[center_y][i+1] == 255 and mask[center_y][i-1] ==0:
                            print('i ='+str(i))
                            if right_x > i:
                                right_x = i
                    center_x_1 = int(( left_x + right_x ) / 2)
#				print('distance_left ='+str(distance_left))
#				print('distance_right ='+str(distance_right))
                    if center_x_1 < 160:
                        print('turn right')
                        self.lib.send_cmd(1560,1200)
                    else:
                        print('turn left')
                        self.lib.send_cmd(1560,1800)
                else:
                    self.lib.send_cmd(1560, angle)
        else:
            self.lib.send_cmd(1560, angle)

    def overtake(self, detect, label_ids, scores, boxes, vel, angle):
        if detect:
            print('overtake_flag : '+ str(self.overtake_flag))
            for label_id, box in zip(label_ids, boxes):
                xmin, ymin, xmax, ymax = box[0], box[1], box[2], box[3]
                xmin, xmax = (int(x / 608 * 320) for x in [xmin, xmax])
                ymin, ymax = (int(y / 608 * 240) for y in [ymin, ymax])
                center_x = int((xmin + xmax) / 2)
                center_y = int((ymin + ymax) / 2)
                print(center_x,center_y)
                if center_y > 30:
                    if self.overtake_flag:
                        print('overtake')
                        self.lib.send_cmd(self.init_vels, 2150)
                        time.sleep(1.1)

                        self.lib.send_cmd(self.init_vels, 850)
                        time.sleep(0.8)
                        self.lib.send_cmd(self.init_vels, 1100)
                        time.sleep(0.7)
                        self.overtake_flag = False
                        self.right_flag = True

                        # self.lib.send_cmd(1560, 900)
                        # time.sleep(2.2)
                        # self.lib.send_cmd(1560, 2300)
                        # time.sleep(0.7)
                else:
                    self.lib.send_cmd(self.init_vels, angle)

        else:
            self.lib.send_cmd(self.init_vels, angle)

    def stop(self, detect, label_ids, scores, boxes, vel, angle):
        if detect:
            for label_id, box in zip(label_ids, boxes):
                xmin, ymin, xmax, ymax = box[0], box[1], box[2], box[3]
                xmin, xmax = (int(x / 608 * 320) for x in [xmin, xmax])
                ymin, ymax = (int(y / 608 * 240) for y in [ymin, ymax])
                center_x = int((xmin + xmax) / 2)
                center_y = int((ymin + ymax) / 2)
                label = self.label_dict[label_id]
                if center_y > 60:
                    print('label = ' + self.label)
                    self.lib.send_cmd(1500, 1500)
                else:
                    self.lib.send_cmd(self.init_vels, angle)

        else:
            self.lib.send_cmd(self.init_vels, angle)

    def turn_left(self, detect, label_ids, scores, boxes, vel, angle):
        if detect:
            for label_id, box in zip(label_ids, boxes):
                xmin, ymin, xmax, ymax = box[0], box[1], box[2], box[3]
                xmin, xmax = (int(x / 608 * 320) for x in [xmin, xmax])
                ymin, ymax = (int(y / 608 * 240) for y in [ymin, ymax])
                center_x = int((xmin + xmax) / 2)
                center_y = int((ymin + ymax) / 2)
                label = self.label_dict[label_id]
                if center_y > 150:
                    print('label = ' + self.label)
                    self.lib.send_cmd(vel, 2250)
                    time.sleep(0.3)
                else:
                    self.lib.send_cmd(self.init_vels, angle)
        else:
            self.lib.send_cmd(self.init_vels, angle)

    def limit(self, detect, label_ids, scores, boxes, vel, angle, a):
        if detect:
            for label_id, box in zip(label_ids, boxes):
                xmin, ymin, xmax, ymax = box[0], box[1], box[2], box[3]
                xmin, xmax = (int(x / 608 * 320) for x in [xmin, xmax])
                ymin, ymax = (int(y / 608 * 240) for y in [ymin, ymax])
                center_x = int((xmin + xmax) / 2)
                center_y = int((ymin + ymax) / 2)
                label = self.label_dict[label_id]
                if center_y > 120:
                    if label == 'limit':
                        print('label = ' + self.label)
                        self.limit_flag = True
                        self.lib.send_cmd(self.init_vels,angle)
                    elif label =='limit_end':
                        print('label = ' + self.label)
                        self.limit_flag = False
                        self.lib.send_cmd(self.init_vels,angle)
                else :
                    self.lib.send_cmd(self.init_vels,angle)
        else:
            self.lib.send_cmd(self.init_vels, angle)

    def line(self, mask):
        center_y = 50
        left_x = 0
        right_x = 320
        for j in range(0,160):
            if mask[center_y][j] == 255 and mask[center_y][j+1] == 0 and mask[center_y][j-1] == 255:
                print('j = '+ str(j))
                if left_x < j:
                    left_x = j
        for i in range(160,319):
            if mask[center_y][i] == 255 and mask[center_y][i+1] == 255 and mask[center_y][i-1] ==0:
                print('i ='+str(i))
                if right_x > i:
                    right_x = i
        center_x_1 = int(( left_x + right_x ) / 2)
        print(center_x_1)
#				print('distance_left ='+str(distance_left))
#				print('distance_right ='+str(distance_right))
        if center_x_1 < 142:
            print('turn right')
            self.lib.send_cmd(1535,1200)
        elif center_x_1 >174:
            print('turn left')
            self.lib.send_cmd(1535,1800)
        else:
            print('straight')
            self.lib.send_cmd(1535,1500)

    def user(self, detect, label_ids, scores, boxes, vel, angle, a, mask):
        # print('detect =', detect)
        if detect:
            # print(label_ids, boxes)
            for label_id, box in zip(label_ids, boxes):
                xmin, ymin, xmax, ymax = box[0], box[1], box[2], box[3]
                xmin, xmax = (int(x / 608 * 320) for x in [xmin, xmax])
                ymin, ymax = (int(y / 608 * 240) for y in [ymin, ymax])
                center_x = int((xmin + xmax) / 2)
                center_y = int((ymin + ymax) / 2)
                self.label = self.label_dict[label_id]
                print('label: ' + self.label)
                if self.label == 'limit':
                    self.limit(detect, label_ids, scores, boxes, vel, angle, a)
                    # if center_y > 120:
                    #     print('label = ' + self.label)
                    #     self.limit_flag = True
                if self.label == 'limit_end':
                    self.limit(detect, label_ids, scores, boxes, vel, angle,a)
                    # if center_y > 120:
                    #     print('label = ' + self.label)
                    #     self.limit_flag = False
                if self.label == 'avoiding':
                    self.avoiding(detect, label_ids, scores, boxes, vel, angle, mask)
                    # if center_y > 130:
                    #     print('label = ' + self.label)
                    #     if center_x < 160:
                    #         print('right')
                    #         self.lib.send_cmd(1535, 900)
                    #     elif center_x > 160:
                    #         print('left')
                    #         self.lib.send_cmd(1535, 2100)
                    # else:
                    #     self.lib.send_cmd(1600, angle)
                if self.label == 'stop':
                    self.stop(detect, label_ids, scores, boxes, vel, angle)
                    # if center_y > 60:
                    #     print('label = ' + self.label)
                    #     self.lib.send_cmd(1500, 1500)
                    # else:
                    #     self.lib.send_cmd(1600, angle)
                if self.label == 'back':
                    self.back(detect, label_ids, scores, boxes, vel, angle, mask)
                    # if center_y > 130:
                    #     print('label = ' + self.label)
                    #     self.back_flag = True
                    # else:
                    #     self.lib.send_cmd(1600, angle)
                if self.label == 'overtake':
                    self.overtake(detect, label_ids, scores, boxes, vel, angle)
                    # if center_y > 130:
                    #     print('overtake')
                    #     self.lib.send_cmd(1560, 2100)
                    #     time.sleep(1)
                    # else:
                    #     self.lib.send_cmd(1600, angle)
                if self.label == 'red_line':
                    self.stop(detect, label_ids, scores, boxes, vel, angle)
                    # if center_y > 60:
                    #     print('label = ' + self.label)
                    #     self.lib.send_cmd(1500, 1500)
                    # else:
                    #     self.lib.send_cmd(1600, angle)
                if self.label == 'turn_left':
                    if self.right_flag:
                        self.right_flag = False
                    self.lib.send_cmd(self.init_vels, angle)
                    # if center_y > 150:
                    #     print('label = ' + self.label)
                    #     self.lib.send_cmd(vel, 2250)
                    #     time.sleep(0.3)
                    # else:
                    #     self.lib.send_cmd(1600, angle)
                if self.label == 'outer':
                    self.lib.send_cmd(self.init_vels, angle)

                if self.label == 'straight':
                    self.lib.send_cmd(self.init_vels, angle)

        else:
            self.lib.send_cmd(self.init_vels, angle)

        if self.limit_flag:
            print('limited speed')
            angle = int(-1792 * a * a + 3413 * a + 176.7 + 2)
            self.lib.send_cmd(1528, angle)
            return

        # if self.limit_flag :
        #     print('limited speed')
        #     angle = int(-1792 * a * a + 3413 * a + 176.7 + 2)
        #     self.lib.send_cmd(1528, angle)
        #     return

        # if self.back_flag :
        #     print('backing')
        #     self.lib.send_cmd(500, 1500)
        #     time.sleep(1)
        #     self.lib.send_cmd(1440, 1100)
        #     time.sleep(1.5)
        #     print('the program is dead')
        #     while True:
        #         self.lib.send_cmd(1500, 1500)

        # -----------------------operation module-----------------------#

    # -------------------------------------------- operation system --------------------------------------------#

    # The main program of Lane Identify
    def run_lane(self):
        while True:
            # Access to images, img_label, img_angle, and img_save are the files required by label_predictor,angle_predictor, and img_save
            img_label, img_angle, img_save = self.dataset(self.video)

            # Get vel
            vel = self.init_vels

            # Predict angle, the result interval is [800, 2100]
            angle = self.angle_predict(self.angle_predictor, img_angle)
            angle = int(angle * 1570 + 740)

            self.lib.send_cmd(vel, angle)

    # The main program of Lane Identify and Label Identify
    def run(self):
        while self.run_flag:
            # Access to images, img_label, img_angle, and img_save are the files required by label_predictor,angle_predictor, and img_save
            img_label, img_angle, img_save = self.dataset(self.video)

            # Transform the img_label image into tensor
            paddle_data_feeds = self.tensor_deal(img_label)

            # Get vel
            # vel = self.init_vels
            # Test
            vel = 1600

            # Predict angle, the result interval is [800, 2100]
            a = self.angle_predict(self.angle_predictor, img_angle)

            # Test
            angle = int(-3132 * a * a * a + 5114 * a * a - 522.2 * a + 874.4)

            # Predict label, the results are None(no object) or labels, scores, boxes
            label_outputs = self.label_predictor.Run(paddle_data_feeds)
            label_outputs = np.array(label_outputs[0], copy=False)

            # Get picture parameters
            detect, labels, scores, boxes = self.get_img_para(label_outputs)

            # save img
            # self.img_save(img=img_save, detect=detect, boxes=boxes, labels=labels, scores=scores)

            # Sends data to the control program
            self.user_cmd(detect, labels, scores, boxes, vel, angle, a)

        if not self.run_flag:
            self.lib.send_cmd(1500, 1500)

    def run_avoiding(self):
        while True:
            # Access to images, img_label, img_angle, and img_save are the files required by label_predictor,angle_predictor, and img_save
            img_label, img_angle, img_save, mask = self.dataset(self.video)

            # Get vel
            vel = self.init_vels

            # Predict angle, the result interval is [800, 2100]
            # a = self.angle_predict(self.angle_predictor, img_angle)

            # Test
            # angle = int(-3132 * a * a * a + 5114 * a * a - 522.2 * a + 874.4)
            if self.right_flag :
                a = self.angle_predict(self.angle_right_predictor, img_angle)
                angle = int(3000 * a - 20)
                if angle > 2500:
                    angle =850
                elif angle < 860:
                    angle = 860
            else:
                a = self.angle_predict(self.angle_predictor, img_angle)
                angle = int(3000 * a)
#                angle = int(2000 * a + 500)
                print(a)
#                if a < 0.6 and a > 0.4:
#                	angle = int(2000 * a + 500 )

            print('right_flag :' + str(self.right_flag))

            # Transform the img_label image into tensor
            paddle_data_feeds = self.tensor_deal(img_label)

            # Predict label, the results are None(no object) or labels, scores, boxes
            label_outputs = self.label_predictor.Run(paddle_data_feeds)
            label_outputs = np.array(label_outputs[0], copy=False)

            # Get picture parameters
            detect, labels, scores, boxes = self.get_img_para(label_outputs)
#            if len(label_outputs.shape) > 1:
#                        for output in label_outputs:
#                            label = output[0]
#                            score = output[1]
#                            print('label = ' + str(self.label_dict[label]) + ', score = ' + str(score))
#                            self.img_save(img=img_save, detect=detect, boxes=boxes, labels=labels, scores=scores)

#             save img
            if not detect:
                self.img_save(img=img_save, detect=detect, boxes=boxes, labels=labels, scores=scores)
                print('save img')

            # Sends data to the control program
            # self.follow(detect, labels, scores, boxes, vel)

            # control program
            # print('angle = '+str(angle))
            self.user(detect, labels, scores, boxes, vel, angle, a, mask)
            # self.line(mask)
            # print("detect ok")

if __name__ == '__main__':
    car = Car()
    car.run_avoiding()


import random

def Check_Num(n):
    if n > N:
        return("down")
    elif n < N:
        return("up")
    else:
        return("success")

N = random.randint(1, 100)
while True:
    n = int(input("수 입력 :"))
    res = Check_Num(n)
    print(res)
    if res == "success":
        break


import requests
from time import sleep
import os
import sys
import json

TOO_MANY_REQUESTS = 6
path_for_config = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.json')
path_for_group = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'groups.json')

def do_request(url, parameters):
    base_params = {
        'v': VERSION,
        'access_token': TOKEN,
    }
    base_params.update(parameters)
    while True:
        response = requests.get(url, base_params)
        print('.', end='')
        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError as err:
            print('It is not a 200 error code: ' + str(err))
            sys.exit()
        data = response.json()
        if 'error' in data:
            if int(data['error']['error_code']) == TOO_MANY_REQUESTS:
                sleep(0.4)
                continue
            else:
                result = None
                break
        else:
            result = data['response']
            break
    print(' ')
    return result

def get_friends_list():
    params = {
        'user_id': VKID,
    }
    friends_ids = do_request('https://api.vk.com/method/friends.get', params)['items']
    return friends_ids

def get_group_by_friend_list(friend_list):
    group_idents = []
    for friend in friend_list:
        params = {
            'user_id': friend,
        }
        result = do_request('https://api.vk.com/method/groups.get', params)
        if result is None:
            continue
        else:
            group_idents.extend(result['items'])
    group_idents = set(group_idents)
    return group_idents

def unique_groups_detect(friends_groups):
    params = {
        'user_id': VKID,
    }
    users_groups = do_request('https://api.vk.com/method/groups.get', params)['items']
    users_groups = set(users_groups)
    unique_groups = users_groups - friends_groups
    unique_groups = list(unique_groups)
    return unique_groups

def get_unique_group_data(list_of_groups):
    result = ','.join([str(group) for group in list_of_groups])
    params = {
        'fields': 'members_count',
        'group_ids': result,
        'extended': 1
    }
    list_of_group = do_request('https://api.vk.com/method/groups.getById', params)
    list_of_group_final = []
    for group in list_of_group:
        dict_of_data = {'id': group['id'], 'name': group['name'], 'members_count': group['members_count']}
        list_of_group_final.append(dict_of_data)
    print('Количество уникальных групп пользователя {} - {}'.format(VKID, len(list_of_group_final)))
    return list_of_group_final

def write_result_to_json(group_list, file_path):
    with open(file_path, 'w') as resultfile:
        json.dump(group_list, resultfile, ensure_ascii=False)

with open(path_for_config, 'r') as f:
    config_data = json.loads(f.read())
    TOKEN = config_data['token']
    VKID = config_data['vkid']
    VERSION = config_data['version']

if __name__ == '__main__':
    friend_ids = get_friends_list()
    group_ids = get_group_by_friend_list(friend_ids)
    group_data = unique_groups_detect(group_ids)
    write_result_to_json(get_unique_group_data(group_data), path_for_group)


t = int(input())
for test_case in range(t):
    answer = 0
    l, u, x = map(int, input().split())
    if u < x:
        answer = -1
    elif l > x:
        answer = l - x

    print(f'#{test_case+1} {answer}')

3431. 준환이의 운동관리.py


import os
from models.detector import Detector
from pycocotools.cocoeval import COCOeval
import pycocotools.coco as coco
import pycocotools.mask as mask_util
import numpy as np
from tqdm import tqdm
from config import cfg as opt
os.environ['CUDA_VISIBLE_DEVICES'] = '3'
valid_ids = [
            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13,
            14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
            24, 25, 27, 28, 31, 32, 33, 34, 35, 36,
            37, 38, 39, 40, 41, 42, 43, 44, 46, 47,
            48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
            58, 59, 60, 61, 62, 63, 64, 65, 67, 70,
            72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
            82, 84, 85, 86, 87, 88, 89, 90]

## config recover weights
opt.weights = 'exp/coco_person/model_last.pth'
opt.vis_trehs = 0.01
split = 'val'

detector = Detector(opt)
data = coco.COCO(os.path.join(
            opt.data_dir, 'annotations',
            'instances_{}2017.json').format(split))

if opt.class_name!='*' :  ## for one class
    catIds = data.getCatIds(opt.class_name)
    imgIds = data.getImgIds(catIds=catIds)
    valid_ids = catIds

detections = []
for img_id in tqdm(data.getImgIds()):
    img_name = os.path.join(os.path.join(opt.data_dir, '{}2017'.format(split)),
                            data.loadImgs(ids=[img_id])[0]['file_name']).strip()
    boxs,masks = detector.run(img_name,vis=False)
    for i,det in enumerate(boxs):
        x, y, x1, y1, conf, cls = det[:6]
        detection = {
            "image_id": img_id,
            "category_id": int(valid_ids[int(cls)]),
            'segmentation':mask_util.encode(np.asfortranarray(masks[i])),
            #"bbox": [x, y, x1 - x, y1 - y],
            "score": float("{:.2f}".format(conf))
        }
        detections.append(detection)
coco_dets = data.loadRes(detections)
coco_eval = COCOeval(data, coco_dets, "segm")

if opt.class_name!='*':  ## for one class
    coco_eval.params.imgIds = imgIds
    coco_eval.params.catIds = catIds

coco_eval.evaluate()
coco_eval.accumulate()
coco_eval.summarize()


# encoding: utf-8

import requests
import json

def get_weather(url):
    result = requests.get(url)
    if result.status_code == 200:
        return result.json()
    else:
        return('Не могу получить данные о погоде!')

def get_names(url='http://api.data.mos.ru/v1/datasets/2009/rows', year=None):
    if year in [2015, 2016]:
        url = url + '/?$filter=Cells/Year eq ' + str(year)

    result = requests.get(url)

    if result.status_code == 200:
        return result.json()
    else:
        return('Не могу получить имена!')
        raise

if __name__ == '__main__':
    #print(get_weather('http://api.openweathermap.org/data/2.5/weather?id=524901&units=metric&APPID=2853a176be5333d336775ad3cfb4027b'))
    print(get_names())


# https://www.acmicpc.net/problem/17298
import sys

n = int(sys.stdin.readline().strip())
num = list(map(int, sys.stdin.readline().split()))

result = [-1] * n
stack = []

for i in range(n):
    while stack and (stack[-1][0] < num[i]):  # 스택이 비어있지 않고 스택 맨 위가 num[i]보다 작을때까지
        tmp, idx = stack.pop()
        result[idx] = num[i]  # idx에 num[i] 추가
    stack.append([num[i], i])  # 스택이 비어있으면 현재 값 추가
print(*result)


import cv2
import os
from concurrent.futures import ThreadPoolExecutor
import sys
import getopt
import subprocess
from numpy import arange
from itertools import repeat
import moviepy.editor as editor

def Worker(a_InputFile, a_OutputFileName, a_Scale, a_FrameChunkCount, a_CurrID, a_TotalFrameCount):
    print("Starting processing on chunk", a_CurrID)
    BeginFrame = a_CurrID * a_FrameChunkCount + 1
    if a_CurrID == 0:
        BeginFrame = 0

    EndFrame = a_FrameChunkCount + (a_FrameChunkCount * a_CurrID)
    if EndFrame + 1 == a_TotalFrameCount:
        EndFrame += 1

    if EndFrame > a_TotalFrameCount:
        EndFrame = a_TotalFrameCount

    Cmd = ('veai.exe -i "' + a_InputFile + '" '
              '-o "' + os.path.dirname(os.path.abspath(a_InputFile)) + '\\' + a_OutputFileName + '_' + str(a_CurrID) + '.mp4" '
              '-f mp4 '
              '-m ghq-1.0.1 '
              '-s ' + str(a_Scale) + ' '
              '-c ' + str(a_CurrID) + ' '
              '-b ' + str(int(BeginFrame)) + ' '
              '-e ' + str(int(EndFrame)))

    Status = subprocess.call(Cmd, shell=True)
    print("Processing finished on chunk", a_CurrID)
    return Status

def Process(a_InputFile, a_OutputFileName, a_Scale, a_GPUCount, a_ConcatenateVids):
    if not os.path.exists('C:\\Program Files\\Topaz Labs LLC\\Topaz Video Enhance AI'):
        print("Topaz Video Enhance AI was not found on your system.")
        return

    os.chdir('C:\\Program Files\\Topaz Labs LLC\\Topaz Video Enhance AI')
    Capture = cv2.VideoCapture(a_InputFile)
    if Capture.isOpened() is False:
        print("Video stream could not be opened.")
        return

    FrameCount = int(Capture.get(cv2.CAP_PROP_FRAME_COUNT)) - 1
    print("Video frame count:", FrameCount)

    ChunkSize = float(FrameCount) / a_GPUCount
    ChunkSize = int(abs(ChunkSize))
    print("Chunk processing size:", ChunkSize)

    IDs = arange(0, a_GPUCount)
    print("Executing upscaling, this may take a while...")
    with ThreadPoolExecutor(max_workers=a_GPUCount) as Exec:
        Results = Exec.map(Worker, repeat(a_InputFile), repeat(a_OutputFileName),
                           repeat(a_Scale), repeat(ChunkSize), IDs, repeat(FrameCount))

    Success = True
    for Result in Results:
        if Result != 0:
            Success = False
            break

    if not Success:
        print("Upscaling failed.")
        return
    else:
        print("Upscaling successful")

    if a_ConcatenateVids:
        print("Concatenating chunks into single video file...")
        os.chdir(os.path.dirname(os.path.abspath(a_InputFile)) + '\\')
        Videos = []
        for Index in range(0, a_GPUCount):
            Videos.append(editor.VideoFileClip(a_OutputFileName + '_' + str(Index) + '.mp4'))

        FinalVideo = editor.concatenate_videoclips(Videos)
        FinalVideo.write_videofile(a_OutputFileName + '_' + 'Final.mp4')
        print("Done writing concatenated video file.")
        Input = input("Do you want to delete the chunk clips? (Y/N)")
        if Input == 'Y':
            for Index in range(0, a_GPUCount):
                os.remove(a_OutputFileName + '_' + str(Index) + '.mp4')

    print("Finished.")
    os.system('pause')

def Main(a_Args):
    try:
        Options, Arguments = getopt.getopt(a_Args, "hi:o:g:s:c")
    except getopt.GetoptError as err:
        print("Chunkify.py -h for instructions")
        return

    if len(Options) == 0:
        print("Chunkify.py -h for instructions")
        return

    ReqOptionCheck = False
    OutName = "video"
    GPUCount = 1
    Scale = 2.0
    InPath = ""
    ConcatenateVid = False
    for Option, Argument in Options:
        if Option == "-i":
            ReqOptionCheck = True
            InPath = Argument
        elif Option == "-o":
            OutName = Argument
        elif Option == "-g":
            GPUCount = int(Argument)
        elif Option == "-s":
            Scale = float(Argument) / 100
        elif Option == "-c":
            if Argument == "Y":
                ConcatenateVid = True
        else:
            print("Chunkify - Evenly divide upscaling workload over multiple GPUs\n"
                  "\n"
                  "-i (Required) <Video input path> - Specify the video to upscale.\n"
                  "-o <Output name> - Specify the name of the generated video (default is: video).\n"
                  "-g <GPU count> - Specify the amount of GPUs present on this system (default is 1).\n"
                  "-s <Scale> - Specify the desired upscaling percentage (100 for 100%, 600 for 600% etc)(default is 200).\n"
                  "-c - Provide flag to toggle whether to concatenate the created video chunks into one video.\n")

            return

    if ReqOptionCheck is True:
        Process(InPath, OutName, Scale, GPUCount, ConcatenateVid)
    else:
        print("Chunkify.py -h for instructions")

if __name__ == '__main__':
    Main(sys.argv[1:])