import os
import cv2
from skimage.filters import threshold_otsu, threshold_adaptive
from skimage import filters
import numpy as np
from matplotlib import pyplot as plt
from scipy import signal
from smooth import smooth
from savitzky_golay_filter import savitzky_golay
from scipy.signal import argrelextrema
import scipy.fftpack
from skimage.filters import threshold_otsu, threshold_adaptive

# def getseperatingPoints (points,up=0,down=1):
#     result = []
#     for i in range(down, len(points)):
#         if ((points[i]-1) != points[i-1]):
#             result.append(np.mean(points[down-1:i], dtype=int))
#             down = i+1
#         elif (i == (len(points)-1)):
#             result.append(np.mean(points[down-1:i+1], dtype=int))
#     return result

def getseperatingPoints(points):
	pos = 0
	results = [pos]
	for i,j in zip(points[:-1], points[1:]):
		# print(points.index(i))
		if (i != (j-1)):
			# print(points[pos:points.index(i)])
			# print(pos, points.index(i))
			# print(np.mean(points[pos:points.index(i)]))
			results.append(np.mean(points[pos:points.index(j)], dtype=int))
			# results.append(points[pos])
			pos = points.index(i)
		elif (points.index(j) == len(points)-1):
			# print(points.index(i))
			results.append(np.mean(points[pos:points.index(j)], dtype=int))
			# results.append(points[pos])
	return results

def basic_parameters_estimation(img, path, nth):
	# blur_img = filters.gaussian_filter(img, sigma=1, truncate=1)
	# otsu_threshold = threshold_otsu(blur_img)
	# bin_img = (blur_img < otsu_threshold) > 0
	# gray_img = (bin_img*255).astype('uint8')

	h, w = np.shape(img)[:2]
	print(w, h)
	# bin_img = ~(img > 0)*1
	otsu_threshold = threshold_otsu(img)
	bin_img = (img < otsu_threshold) > 0
	gray_img = (bin_img*255).astype('uint8')
	# num, labels = cv2.connectedComponents(gray_img, connectivity = 8)

	ret, labels = cv2.connectedComponents(gray_img, connectivity = 8)

	# Map component labels to hue val
	label_hue = np.uint8(179*labels/np.max(labels))
	blank_ch = 255*np.ones_like(label_hue)
	labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])

	# cvt to BGR for display
	labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)

	# set bg label to black
	labeled_img[label_hue==0] = 0
	# cv2.imwrite(os.path.join(os.getcwd(), "{}.png".format(nth)), labeled_img)
	# plt.imshow(labeled_img)
	# plt.show()

	count = 0
	for i in range(1,ret):
		cc_img = np.zeros_like(img)
		cc_img[labels == i] = 255
		# plt.imshow(cc_img)
		# plt.show()
		x, y, width, height = cv2.boundingRect(cc_img)
		# cv2.imwrite(os.path.join(path, "{}.png".format(count)), cc_img)
		cv2.imwrite(os.path.join(path, "{}_{}.png".format(nth, count)), img[y:y+height, x:x+width])
		# plt.imshow(img[y:y+width, x:x+width])
		# plt.show()
		count += 1

	# plt.imshow(gray_img)
	# plt.show()

if __name__ == "__main__":

    import os
    import glob
    import argparse
    import shutil

    parser = argparse.ArgumentParser(description="Word Segmentation")
    parser.add_argument('--folder', dest='folder', type=str, help="folder to save")
    parser.add_argument('--path', dest='path', type=str, help="path to linecuts")
    # parser.add_argument('--folder', dest='folder', type=str, help="folder to save")
    args = parser.parse_args()

    # save_folder = os.path.join(os.getcwd(), "training_data_")
    save_folder = args.folder
    # if os.path.exists(save_folder):
    # 	shutil.rmtree(save_folder)
    # os.makedirs(save_folder)

    # path = "/home/thanh/Desktop/test_data_difficult-4/line_1.png"
    # img = cv2.imread(path, 0)
    # plt.imshow(img)
    # plt.show()
    # blur_img = filters.gaussian_filter(img, sigma=1, truncate=1)
    # otsu_threshold = threshold_otsu(blur_img)
    # bin_img = (blur_img < otsu_threshold) > 0
    # gray_img = (bin_img*255).astype('uint8')

    # plt.imshow(gray_img)
    # plt.show()
    # cv2.imwrite("debug.png", gray_img)
    # basic_parameters_estimation(img, save_folder, 0)

    for nth, folder in enumerate(os.listdir(args.path)):
    	# img = cv2.imread(os.path.join(args.path,file), 0)
    	# basic_parameters_estimation(img, save_folder, nth)
    	# name = os.path.basename(os.path.dirname(os.path.join(args.path, folder)))
    	name = os.path.basename(os.path.join(args.path, folder))
    	print(name)
    	for file in os.listdir(os.path.join(args.path, folder)):
    		filename = os.path.join(args.path, folder, file)
    		# print(filename)
    		print(os.path.join(save_folder, name+"_"+file))
    		im = cv2.imread(filename)
    		cv2.imwrite(os.path.join(save_folder, name+"_"+file), im)


#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import sys
import time
import json
import subprocess
import threading

from datetime import datetime
from socketserver import ThreadingMixIn
from http.server import HTTPServer, BaseHTTPRequestHandler

from ProcReader.settings import (READER_PATH, READERS_LIST)

def not_insance_address_string(self):
    host, port = self.client_address[:2]
    return '%s (no getfqdn)' % host

BaseHTTPRequestHandler.address_string = not_insance_address_string

class Handler(BaseHTTPRequestHandler):
    content = {}
    intvl = 10
    ts_get = ''
    reader_path = READER_PATH
    readersters = READERS_LIST

    def do_GET(self):
        args_str = 'python %s/ReaderManager.py restart' % (Handler.reader_path)
        if self.path == '/getdata':
            self.send_response(200)
            self.send_header("Content-type", "text/json")
            Handler.ts_get = time.asctime(time.localtime())

            t_content = datetime.strptime(
                Handler.content['timestamp'], "%a %b %d %H:%M:%S %Y")
            t_last_get = datetime.strptime(
                Handler.ts_get, "%a %b %d %H:%M:%S %Y")

            if (t_last_get - t_content).seconds < 60:
                Handler.content['status'] = 'NORMAL'
            else:
                Handler.content['status'] = 'READERING_TIMEOUT'
                Handler.content['data'] = {}
                ping_Popen = subprocess.Popen(args=args_str, shell=True)
            obj_str = json.dumps(Handler.content)
            self.send_header("Content-Length", str(len(obj_str)))
            self.end_headers()
            self.wfile.write(obj_str.encode())
            self.wfile.write('\n')
        elif self.path == '/getintvl':
            self.send_response(200)
            self.end_headers()
            self.wfile.write(Handler.intvl)
            self.wfile.write('\n')
        elif self.path == '/getreadersters':
            self.send_response(200)
            self.send_header("Content-Length", "text/json")
            reader_str = json.dumps(Handler.readersters)
            self.send_header("Content-Length", str(len(reader_str)))
            self.end_headers()
            self.wfile.write(reader_str.encode())
            self.wfile.write('\n')
        elif self.path == '/rstsvr':
            ping_Popen = subprocess.Popen(args=args_str, shell=True)
            self.send_response(200)
            self.end_headers()
            self.wfile.write('Restart server OK!')
            self.wfile.write('\n')
        else:
            self.send_response(404)
            self.end_headers()

    def do_POST(self):
        if self.path == '/setdata':
            length = self.headers['content-length']
            data = self.rfile.read(int(length))
            Handler.content = eval(data.encode())
            self.send_response(200)
            self.end_headers()
            self.wfile.write(str(Handler.content))
            self.write.write('\n')
        elif self.path == '/setintvl1':
            length = self.headers['content-length']
            data = self.rfile.read(int(length))
            Handler.intvl = eval(data.encode())
            self.send_response(200)
            self.end_headers()
            self.wfile.write(str(Handler.intvl))
            self.write.write('\n')
        elif self.path == '/setreadersters':
            length = self.headers['content-length']
            data = self.rfile.read(int(length))
            Handler.readersters = eval(data.decode())
            self.send_response(200)
            self.end_headers()
            self.wfile.write(str(Handler.readersters))
            self.wfile.write('\n')
        else:
            self.send_response(404)
            self.end_headers()

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""

if __name__ == '__main__':
    server = None
    try:
        server = ThreadedHTTPServer(('0.0.0.0', 4396), Handler)
        if sys.argv[1]:
            Handler.reader_path = sys.argv[1]
        print('Starting server, use <Ctrl-C> to stop')
        server.serve_forever()
    except Exception as e:
        if server:
            server.socket.close()


import datetime
import json
import os
import shutil
import sys
from json import JSONDecodeError

import requests

import console
import util

proxies = None
auth = None

base_cache_dir = './checkConfig'
clear_cache = 'none'
cacheTimeout = 365

class CardRetrievalError(Exception):
    def __init__(self, message, card_name, error_code):
        super(CardRetrievalError, self).__init__(message)
        self.cardName = card_name
        self.errorCode = error_code

class ConfigurationError(Exception):
    def __init__(self, message):
        super(ConfigurationError, self).__init__(message)

def get_cache_dir():
    base_dir = os.path.join(os.path.dirname(sys.argv[0]), base_cache_dir, ".scryfallCache")
    if not os.path.exists(base_dir):
        os.makedirs(base_dir)
    return base_dir

def flushCache():
    try:
        shutil.rmtree(get_cache_dir())
    except OSError as e:
        print("Error where clearing cache directory at " + get_cache_dir() + ": %s - %s." % (e.filename, e.strerror))

def initCache(collection):
    last_length = 0
    count = 1

    for card in collection:

        status_line = 'Fetching card info (' + str(count) + '/' + str(len(collection)) + ', ...' + str(
            collection[card].sourceFile)[-50:-2] + '): ' + card + " ..."

        count += 1
        currentLength = len(status_line)
        if currentLength < last_length:
            status_line = status_line + (last_length - currentLength) * ' '
        # newline before doing "status"
        if last_length == 0:
            sys.stdout.write('\n')
        last_length = currentLength

        sys.stdout.write('\r' + status_line)
        sys.stdout.flush()
    doneMessage = ''
    sys.stdout.write('\r' + doneMessage + (last_length - len(doneMessage)) * " " + '\r')
    sys.stdout.flush()

def fetchCardJson(card, json_file, retry_times=3):
    response = requests.get("http://api.scryfall.com/cards/named", params={'exact': card.techName}, proxies=proxies,
                            auth=auth)
    fuzzy_result = False
    if response.status_code == 404:
        print()
        print(console.CRED + "Card '" + card.techName + "' (" + util.absolutePaths(
            card.sourceFile) + ") Was not found in scryfall using exact search." + console.CEND + " Trying fuzzy search.")
        response = requests.get("http://api.scryfall.com/cards/named", params={'fuzzy': card.techName}, proxies=proxies,
                                auth=auth)
        fuzzy_result = True
        if response.status_code < 400:
            print("\'" + card.techName + "\' found as \'" + response.json()[
                "name"] + "\'. " + console.CRED + "Fix files " + util.absolutePaths(card.sourceFile) + console.CEND)
    if (response.status_code == 503 or response.status_code == 504) and retry_times > 0:
        sys.stderr.write('Retrying ' + response.url)
        fetchCardJson(card, json_file, retry_times - 1)
    elif response.status_code >= 400 or retry_times == 0:
        raise CardRetrievalError(
            'Bad response ' + str(response.status_code) + ' for ' + card.techName + "' (" + util.absolutePaths(
                card.sourceFile) + ")",
            card.techName, response.status_code)
    if not fuzzy_result:
        with open(json_file, 'w') as f:
            json.dump(response.json(), f)
    return response.json()

def getCachedCardJson(card):
    jsonFile = os.path.join(get_cache_dir(), util.cleanFilename(card) + ".json")
    if os.path.exists(jsonFile):
        fileAge = datetime.date.today() - datetime.date.fromtimestamp(os.path.getmtime(jsonFile))

        if (clear_cache == 'always' or (clear_cache == 'timeout' and fileAge.days > cacheTimeout) or (
                clear_cache == 'price' and fileAge.days > 1)):
            return fetchCardJson(card, jsonFile)
        else:
            # print("Loading cached " + jsonFile)
            with open(jsonFile, encoding='utf-8') as json_data:
                try:
                    return json.load(json_data)
                except JSONDecodeError:
                    print("Deleting and retrying invalid " + jsonFile)
                    json_data.close()
                    os.remove(jsonFile)
                    return fetchCardJson(card, jsonFile)
    else:
        # print("Loading online " + jsonFile)
        return fetchCardJson(card, jsonFile)

def searchByCard(card):
    url = card.jsonData['prints_search_uri']

    json_file = os.path.join(get_cache_dir(), card.jsonData["oracle_id"] + ".prints.json")
    if os.path.exists(json_file):
        file_age = datetime.date.today() - datetime.date.fromtimestamp(os.path.getmtime(json_file))

        if (clear_cache == 'always' or (clear_cache == 'timeout' and file_age.days > cacheTimeout) or (
                clear_cache == 'price' and file_age.days > 1)):
            return fetchCardJson(card, json_file)
        else:
            # print("Loading cached " + jsonFile)
            with open(json_file, encoding='utf-8') as json_data:
                try:
                    return json.load(json_data)
                except JSONDecodeError:
                    print("Deleting and retrying invalid " + json_file)
                    json_data.close()
                    os.remove(json_file)
                    return searchByCard(card)

    response = requests.get(url, proxies=proxies, auth=auth)

    foundCardsJson = []

    while response is not None and response.status_code == 200:

        jsonResponse = response.json()

        for card in jsonResponse['data']:
            foundCardsJson.append(card)

        if jsonResponse['has_more']:
            response = requests.get(jsonResponse['next_page'], proxies=proxies, auth=auth)
        else:
            response = None

    with open(json_file, 'w') as f:
        json.dump(foundCardsJson, f)

    return foundCardsJson

def search(query):
    response = requests.get('https://api.scryfall.com/cards/search', params={'q': query}, proxies=proxies, auth=auth)

    foundCardNames = []

    while response is not None and response.status_code == 200:

        jsonResponse = response.json()

        for card in jsonResponse['data']:
            foundCardNames.append(card['name'])

        if jsonResponse['has_more']:
            response = requests.get(jsonResponse['next_page'], proxies=proxies, auth=auth)
        else:
            response = None

    return foundCardNames

def getTokenByUrl(url):
    response = requests.get(url, proxies=proxies, auth=auth)
    if response is not None and response.status_code == 200:
        return response.json()
    else:
        return None

def get_set_data(set_code):
    json_file = os.path.join(get_cache_dir(), set_code + "_set.json")
    if os.path.exists(json_file):
        with open(json_file, encoding='utf-8') as json_data:
            try:
                return json.load(json_data)
            except JSONDecodeError:
                print("Deleting and retrying invalid " + json_file)
                json_data.close()
                os.remove(json_file)
                return get_set_data(set_code)
    else:
        response = requests.get('https://api.scryfall.com/sets/' + set_code, proxies=proxies, auth=auth)
        if response.status_code == 200:
            with open(json_file, 'w') as f:
                json.dump(response.json(), f)
            return response.json()
        else:
            return dict()


import random
import numpy as np
import matplotlib.pyplot as plt

def coin_flip():
    return random.randint(0,1)

def monte_carlo(n):
    #n defines the coin flipping times
    Probability = []
    Result = 0
    for i in range(n):
        if coin_flip() == 1:
            Result += 1
        else:
            Result = Result
        Probability.append(Result/(i+1))

    plt.axhline(y = 0.5, color = 'r', linestyle = '-')
    plt.xlabel('Flip')
    plt.ylabel('Probability')
    plt.plot(Probability)
    plt.show(block=False)

    return Probability[-1]

if __name__ == "__main__":
    m = 5
    n = 5000
    Probability_sum = 0
    for i in range(m):
        Probability_sum += monte_carlo(n)
    final_Probability = Probability_sum/m

    print('After {} coin flipping, the probability of head is {}'.format(m*n, final_Probability))


import datetime

today = datetime.date.today()
# print(today)

# print(today.weekday())
# print(today.isoweekday())

# lets calculate a duration of 7 days using timedelta
tdelta = datetime.timedelta(days=7)

# you can add or subtract time delta
# print(today - tdelta)

# diff between two dates is timedelta
bday = datetime.date(2020, 9, 12)
till_bday = bday - today
print(till_bday)

# this was about dates,
# now lets talk about time

t1 = datetime.datetime(2020, 11, 22, 9, 30, 45, 100000)
# print(t1.date())
# print(t1.time())
# print(t1.year)
# print(t1.month)

tdelta = datetime.timedelta(hours=2)
# print(t1 + tdelta)

# constructor with datetime

t11 = datetime.datetime.today()
t12 = datetime.datetime.now()
t13 = datetime.datetime.utcnow()

# print(t11)
# print(t12)
# print(t13)

# using pytz for time zone information
import pytz

# timezone aware UTC

# dt = datetime.datetime(2020, 1, 22, 9, 45, 59, 100000, tzinfo=pytz.UTC)

# print(dt)

dt_now = datetime.datetime.now(tz=pytz.UTC)
print(dt_now)

my_timezone = dt_now.astimezone(pytz.timezone('Asia/Kolkata'))

print(my_timezone)

# for tz in pytz.all_timezones:
# 	print(tz)

dt_kol = datetime.datetime.now(tz = pytz.timezone('Asia/Kolkata'))

# convert the date to string format
print(dt_kol.strftime('%B %d, %Y'))

# convert string to date
str_dt = 'July 26, 2012'

dt = datetime.datetime.strptime(str_dt, '%B %d, %Y')
print(dt)


from skimage import io
from sklearn.cluster import KMeans
import numpy as np
import warnings
import os

warnings.filterwarnings('ignore')

def read_image(file_path: str) -> np.ndarray:
    """
    读取图片文件并返回对应的NumPy数组。
    """
    img = io.imread(file_path)
    return img

def kmeans_clustering(image: np.ndarray, k: int) -> tuple:
    """
    使用K均值聚类对图像进行分组，并返回聚类结果和中心点。
    """
    img_ori_shape = image.shape
    img_flat = image.reshape((img_ori_shape[0] * img_ori_shape[1], img_ori_shape[2]))

    n_channels = img_flat.shape[1]

    estimator = KMeans(n_clusters=k, max_iter=4000, init='k-means++', n_init=50)
    estimator.fit(img_flat)

    centroids = estimator.cluster_centers_
    labels = estimator.labels_

    return centroids, labels, n_channels

def visualize_colors(centroids: np.ndarray, labels: np.ndarray, k: int) -> None:
    """
    可视化聚类结果，输出每个聚类中心的颜色以及对应的比例。
    """
    color_labels = list(labels)
    color_info = {}

    for center_index in range(k):
        color_ratio = color_labels.count(center_index) / len(color_labels)
        color_info[color_ratio] = centroids[center_index]

    color_info = [(k, color_info[k]) for k in sorted(color_info.keys(), reverse=True)]

    for color in color_info:
        print('比例：', color[0], '颜色：', color[1])

def generate_visualization_matrix(centroids: np.ndarray, k: int, result_width: int, result_height_per_center: int) -> np.ndarray:
    """
    使用聚类结果生成一个矩阵，用于数据可视化。
    """
    result = []

    for center_index in range(k):
        result.append(np.full((result_width * result_height_per_center, n_channels), centroids[center_index], dtype=int))

    result = np.array(result)
    result = result.reshape((result_height_per_center * k, result_width, n_channels))

    # 转换数据类型为uint8
    result = result.astype(np.uint8)

    return result

def save_visualization_result(image_file: str, result: np.ndarray) -> None:
    """
    保存可视化结果图片。
    """
    io.imsave(os.path.splitext(image_file)[0] + '_result.png', result)

# 主程序
img_file = 'city.jpg'
k_value = 5
result_width_value = 200
result_height_per_center_value = 80

image = read_image(img_file)
centroids, labels, n_channels = kmeans_clustering(image, k_value)

visualize_colors(centroids, labels, k_value)

visualization_matrix = generate_visualization_matrix(centroids, k_value, result_width_value, result_height_per_center_value)

save_visualization_result(img_file, visualization_matrix)


import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatch
import numpy as np
import string
p = np.linspace(16/0.254,20/0.254,10000)
startTheta = np.arcsin((3/2.)**0.5)
startThetaPhi = -np.pi/4
startThetaPhie = np.pi/4
endTheta = np.pi/2
theta = [startTheta-PMTtheta]
tmptheta = theta[-1]-PMTtheta*3**0.5
weiduyuanR = R*np.sin(tmptheta)
thisArcAngle = np.arccos(R/3**0.5/weiduyuanR)
thisArc = thisArcAngle*weiduyuanR
tmpnPMT = R*np.sin(tmptheta)*angle(tmptheta)
m = 6*3**0.5/4/(np.pi*(3**0.5/2)**2)
coverage = (1+(np.pi/8*p).round())*((2./3*p).round()+1)*2/p**2*m
print ((2./3*p).round()+1)
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111)
ax.plot(p*0.254,coverage)
plt.show()


from rest_framework import generics, status
from rest_framework.response import Response
from rest_framework.generics import UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from hospital_bed_map_backend.beds.api.serializer import BedsActiveUpdateSerializer, BedsStatusUpdateSerializer, BedsListSerializer, TypeSerializer, BedsSerializer, TypeOccupationSerializer
from hospital_bed_map_backend.beds.models import TypeOccupation, Type, Beds
from hospital_bed_map_backend.sectors.models import Sectors
from django.db.models import F

class TypeView(generics.GenericAPIView):
    serializer_class = TypeSerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        data = Type.objects.all()
        serializer = self.serializer_class(data, many=True).data

        return Response({'message': 'Dados recuperados com sucesso', 'data': serializer}, status=status.HTTP_200_OK)

class TypeOccupationView(generics.GenericAPIView):
    serializer_class = TypeOccupationSerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        data = TypeOccupation.objects.all()
        serializer = self.serializer_class(data, many=True).data

        return Response({'message': 'Dados recuperados com sucesso', 'data': serializer}, status=status.HTTP_200_OK)

class BedsListView(generics.GenericAPIView):
    serializer_class = BedsListSerializer
    permission_classes = [IsAuthenticated]

    def get(self, request, sector=None):

        data = Beds.objects.filter(sector=sector)\
                .values('id', 'sector__hospital', 'sector',
                'name', 'type_occupation', 'type_occupation__status', 'type_occupation__description',
                'type__description', 'is_active', 'is_extra')\
                .annotate(  hospital_id=F('sector__hospital'),
                            sector_id=F('sector'),
                            type_occupation_id=F('type_occupation'),
                            type_occupation_status=F('type_occupation__status'),
                            type_occupation_description=F('type_occupation__description'),
                            type=F('type__description'))

        serializer = self.serializer_class(data, many=True).data

        return Response({'message': 'Dados recuperados com sucesso', 'data': serializer}, status=status.HTTP_200_OK)

class BedsUpdateActiveView(generics.GenericAPIView):
    serializer_class = BedsActiveUpdateSerializer
    permission_classes = [IsAuthenticated]

    def put(self, request, bed=None):
        bed = Beds.objects.filter(id=bed)

        if bed.exists():
            serializer = self.serializer_class(bed, data=request.data, context={'user': request.user})
            if(not(serializer.is_valid())):
                return Response({'message': 'Falha ao atualizar os dados do leito.', 'data': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
            serializer_data = self.serializer_class(serializer.save()).data

        else:
            return Response({'message': 'Leito não encontrado.'}, status=status.HTTP_404_NOT_FOUND)

        return Response({'message': 'Dados do leito atualizado com sucesso.', 'data': [serializer_data]}, status=status.HTTP_200_OK)

class BedsUpdateStatusView(generics.GenericAPIView):
    serializer_class = BedsStatusUpdateSerializer
    permission_classes = [IsAuthenticated]

    def put(self, request, bed=None):
        bed = Beds.objects.filter(id=bed)

        if bed.exists():
            serializer = self.serializer_class(bed, data=request.data, context={'user': request.user})
            if(not(serializer.is_valid())):
                return Response({'message': 'Falha ao atualizar os dados do leito.', 'data': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
            serializer_data = self.serializer_class(serializer.save()).data
            typeOccupation = TypeOccupation.objects.filter(pk=serializer_data['type_occupation']).first()
            data = {
                'id': serializer_data['id'],
                'type_occupation_id': serializer_data['type_occupation'],
                'type_occupation_status': typeOccupation.status,
                'type_occupation_description': typeOccupation.description
            }

        else:
            return Response({'message': 'Leito não encontrado.'}, status=status.HTTP_404_NOT_FOUND)

        return Response({'message': 'Dados do leito atualizado com sucesso.', 'data': [data]}, status=status.HTTP_200_OK)

class BedsDeleteView(generics.GenericAPIView):
    permission_classes = [IsAuthenticated]

    def delete(self, request, bed=None):
        data = Beds.objects.filter(id=bed)

        if(data.exists()):
            id_leito = data.first().pk
            if(data.values('type_occupation__status').first()['type_occupation__status'] == 'OCUPADO'):
                return Response({'message': 'Leito ocupado não pode ser deletado.'}, status=status.HTTP_400_BAD_REQUEST)
            data.delete()

        else:
            return Response({'message': 'Leito não encontrado.'}, status=status.HTTP_404_NOT_FOUND)

        return Response({'message': 'Dados do leito removido com sucesso.', 'data': [{'id': id_leito}]}, status=status.HTTP_200_OK)

class BedsView(generics.GenericAPIView):
    serializer_class = BedsSerializer
    permission_classes = [IsAuthenticated]

    def post(self, request):

        serializer = self.serializer_class(data=request.data, context={'user': request.user})

        if not(serializer.is_valid()):
            return Response({'message': 'Falha ao cadastrar o leito , verifique os dados e tente novamente.', 'data': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)

        data = serializer.save()
        sector = Sectors.objects.filter(id=data.sector.id).first()

        if data.type_occupation is None:
            typeOccupation = TypeOccupation.objects.filter(status='VAGO').first()
        else:
            typeOccupation = TypeOccupation.objects.filter(description=data.type_occupation).first()

        if data.type is None:
            type = None
        else:
            type = Type.objects.filter(description=data.type).first().description

        result = {
            'id': data.pk,
            'hospital_id': sector.hospital.id,
            'sector_id': sector.id,
            'name': data.name,
            'type_occupation_id': typeOccupation.id,
            'type_occupation_status': typeOccupation.status,
            'type_occupation_description': typeOccupation.description,
            'type': type,
            'is_active': data.is_active,
            'is_extra': data.is_extra
        }

        return Response({'message': 'Leito cadasrtado com sucesso', 'data': [result]}, status=status.HTTP_200_OK)


import PIL
import os
from PIL import Image

f = '/home/arvinda/Projects/Sign Language Detection/data/train/what is your name?'   #d for test as well
print(os.listdir(f))

for file in os.listdir(f):
    f_img = f+"/"+file
    img = Image.open(f_img)
    img = img.resize((64, 64))
    img.save(f_img)


import torch
import torch.nn as nn

from models.layers import get_activation_fn

class GraphConv(nn.Module):
    def __init__(self, in_dim: int, out_dim: int, identity_proj: bool = False):
        super().__init__()
        if identity_proj:
            assert in_dim == out_dim
        self.linear = nn.Identity() if identity_proj else nn.Linear(in_dim, out_dim)
        self._reset_parameters()

    def _reset_parameters(self):
        if isinstance(self.linear, nn.Linear):
            nn.init.xavier_uniform_(self.linear.weight)
            nn.init.normal_(self.linear.bias)

    def forward(self, edges: torch.Tensor, feat: torch.Tensor) -> torch.Tensor:
        """
        Args:
            edges: shape: [bs, n, n]
            x: shape: [bs, n, dim]
        """
        # [bs, n, n] [bs, n, dim] -> [bs, n, dim]
        adj = edges + edges.transpose(1, 2)
        In = torch.zeros_like(adj)
        In.diagonal(dim1=1, dim2=2).fill_(1)
        feat = torch.bmm(adj / 2 + In, feat)
        return self.linear(feat)

class Layer(nn.Module):
    def __init__(self, emb_dim: int, activation: str, identity_proj: bool = False):
        super().__init__()
        self.g_conv = GraphConv(emb_dim, emb_dim, identity_proj)
        self.norm = nn.LayerNorm(emb_dim)
        self.activation = get_activation_fn(activation)

    def forward(self, edges: torch.Tensor, feat: torch.Tensor, feat_mask: torch.BoolTensor = None):
        feat = self.g_conv(edges, feat)
        if feat_mask is not None:
            feat.masked_fill_(feat_mask[..., None], 0)
        feat = self.activation(self.norm(feat))
        return feat

class GNN(nn.Module):
    def __init__(
        self,
        num_codes: int,
        embed_dim: int,
        num_layers: int,
        identity_proj: bool = False,
        activation: str = "relu"
    ):
        super().__init__()
        self.num_codes = num_codes
        self.embed_dim = embed_dim
        self.num_layers = num_layers

        self.embedding = nn.Embedding(
            num_embeddings=num_codes + 1,
            embedding_dim=embed_dim,
            padding_idx=num_codes
        )
        layers = [Layer(embed_dim, activation, identity_proj) for _ in range(num_layers)]
        self.layers = nn.ModuleList(layers)
        self.fc = nn.Linear(embed_dim, embed_dim)
        self._reset_parameters()

    def _reset_parameters(self):
        nn.init.normal_(self.fc.weight)
        nn.init.zeros_(self.fc.bias)
        nn.init.trunc_normal_(self.embedding.weight[:self.num_codes])

    def forward(
        self,
        nodes: torch.Tensor,
        edges: torch.Tensor,
        ingredients: torch.LongTensor,
        feat_mask: torch.BoolTensor = None
    ):
        """
        Args:
            nodes: [bs, n]
            edges: [bs, n, n]
        """
        # code embedding [bs, n, dim]
        feat: torch.Tensor = self.embedding(ingredients)
        for layer in self.layers:
            feat = layer(edges, feat, feat_mask)
        # weighted average pooling
        feat = feat * nodes[..., None]
        feat = feat.mean(dim=1)
        feat = self.fc(feat)
        return feat


from rdkit.Chem import AllChem
from rdkit import Chem
from rdkit import RDLogger
from pathlib import Path
import glob, sys
import argparse
RDLogger.DisableLog('rdApp.*')
import pickle

import logging

def set_file_logger(filename: str, name: str = 'candle', level: int = logging.DEBUG, format_string = None):
    """Add a stream log handler.

    Args:
        - filename (string): Name of the file to write logs to
        - name (string): Logger name
        - level (logging.LEVEL): Set the logging level.
        - format_string (string): Set the format string

    Returns:
       -  None
    """
    if format_string is None:
        format_string = "%(asctime)s.%(msecs)03d %(name)s:%(lineno)d [%(levelname)s]  %(message)s"

    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    handler = logging.FileHandler(filename)
    handler.setLevel(level)
    formatter = logging.Formatter(format_string, datefmt='%Y-%m-%d %H:%M:%S')
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger

def process_files(smile_file, out_file, log_file, index_start, batchsize, pickle_out, debug=False):
    import time
    import shutil
    import os
    start = time.time()
    import logging
    import pickle

    from rdkit.Chem import AllChem

    count = 0
    bad_count = 0
    logger = set_file_logger(log_file, level=logging.DEBUG if debug else logging.INFO)
    logger.info(f"Running fingerprint on {smile_file} from index_start:{index_start}")

    tmp_out_file = '/dev/shm/{}'.format(os.path.basename(out_file))

    logger.info(f"Writing output temporarily to {tmp_out_file}")
    smiles = []
    with open(smile_file) as current:
        current.seek(index_start)
        smiles = [current.readline() for i in range(batchsize)]

    with open(tmp_out_file, 'w') as out_handle:
        if pickle_out:
            outputs = []
        for line in smiles:
            smile, *remainder = line.split()
            try:
                logger.debug(f"Processing smile {smile}")
                fprint = AllChem.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=2048).ToBase64()
            except:
                logger.exception("Caught exception")
                fprint = None
                bad_count += 1
            id = remainder[0] if remainder else ''
            if pickle_out:
                outputs += [(smile, id, fprint)]
            else:
                print('{},{},{}'.format(smile, id, fprint), file=out_handle)
            count += 1

    if pickle_out:
        with open(tmp_out_file, 'wb') as f:
            pickle.dump(outputs, f)
    shutil.move(tmp_out_file, out_file)

    logger.info("Bad smile count {}".format(bad_count))
    logger.info("Completed {} smiles from {} in {:8.3f}s".format(count,
                                                                 smile_file,
                                                                 time.time() - start))
    logger.handlers.pop()
    return out_file

def main(argv):
    parser = argparse.ArgumentParser(description='Program to process Moyer maps')
    parser.add_argument('-d', '--debug', help='Debug level', required=False, type=int, choices=[0, 1, 2])
    parser.add_argument('-P', '--profile', help='Profile code', required=False, default=False, action='store_true')
    parser.add_argument('-i', '--input', help='Input file', required=True)
    args = parser.parse_args()

    # Default debug level is 1: set -d 0 for no info at all, -d 2 for verbose info
    if args.debug != None:
        global debug
        debug = args.debug

    if args.profile:
        pr = cProfile.Profile()
        pr.enable()

    if args.input == 'Enamine':
        files = glob.glob('SMILEs/Enamine_Real_SMILEs/2019q3-4_Enamine_REAL_01_canonical_only.smi')
        sep   = '\t'
        process_files(files, sep, None)
    elif args.input == 'pubchem':
        files = ['SMILEs/pubchem_canonical.csv']
        sep   = ','
        process_files(files, sep, 'pubchem')

    if args.profile:
        pr.disable()
        s = io.StringIO()
        sortby = SortKey.CUMULATIVE
        ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
        ps.print_stats()
        print(s.getvalue())

if __name__ == '__main__':
    process_files('/projects/CVD_Research/foster/SMILEs/Enamine_Real_SMILEs/2019q3-4_Enamine_REAL_16_canonical_only.smi',
                  '/projects/candle_aesp/yadu/covid_fingerprinting/test.csv',
                  '/projects/candle_aesp/yadu/covid_fingerprinting/test.log',
                  251,
                  5,
                  debug=True)
    #main(sys.argv[1:])