#%%[markdown]
## Sprawozdanie - GPU
#----
## Środowisko tesotwe
#### GPU:
# * Model: Nvidia GeForce GTX 750Ti
# * 640 CUDA Cores (5 x 128)
# * Global memory: 2002 MB
# * GPU Clock rate: 1110 MHz
# * Memory Clock rate: 2700 MHz
# * Maximum number of thread per block: 1024
# * Maximum number of thread per multiprocessor: 2048 **(64 Warps)**
# * Shared memory per block: 49125 b
# * Max dimension size of thread block: (1024, 1024, 64)
# * CUDA Capability: 5.0
#
#### CPU:
# * Model: Intel i7-4600U
# * Frequency base(boost): 2.1 (3.3) GHz
# * Cores/Thread: 2 / 4
# * Cache: 4 MB
#
#----
## Funkcjonalności i sposobu użytkowania pamięci tekstur
##### Funkcjonalność:
# * Pamięć typu read-only
# * Cache
#   - zoptymalizowany pod kątem dostępności lokalnej 2D,
#     przez co wątki które czytają adresy tekstur blisko siebie powinny osiągać najlepszą wydajność. (spatial locality)
# * Pamięci tekstur najlepiej użyć przy dużej liczbie operacji *read* i małej *write*.
#
##### Sposób użycia:
# * Deklaracja pamięci tekstury w CUDA
# * Binding pamięci tekstury do referencji tekstury
# * Czytanie pamięci tekstury poprzez referencję tekstury
# * Unbinding pamięci tekstury od referencji tekstury
#
## Zachowanie scheduler'a multiprocesora jeśli w kodzie kernela znajduje się instrukcja warunkowa
# * Różne warpy mogą wykonywać całkowicie różny kod.
#   - Różne kontrole przepływu programu, nie wpływają na wydajność.
#   - Każdy warp utrzymuje swój własny licznik.
# * Jeżeli jakaś część warpu musi wykonywać oprację
#   - Wątki które jej nie wykonują są wyłączone (Don’t fetch operands, don’t write output)
# * Wykonanie warunkowe wewnątrz warpu
#   - Jeżeli conajmniej jeden wątek wewnątrz warpu musi wykonać
#   daną ścieżkę w instrukcji kierunkowa, to cały warp zajmuję się tę ścieżkę.
#----
## Problem
# * Rozwiązywanie równania Laplace’a metodą różnic skończonych.
# * 3 warianty GPU wykorzystujące pamięć **globalną**, **współdzieloną**, **tekstur**
# * 1 wariant CPU
#
## Pomiar
# * Skrypt bash do uruchomienia algorymów z wybranymi parametrami
# * Wynik zapisawne do formatu *CSV*: ```grid,block,time,type```
# * Metryka **achieved occupancy** uzyskana za pomocą profilera nvprof (mała liczba pomiarów)
#
### Parametry
# * czas/delta symulacji: **0.5 / 0.00001**
# * Rozmiar Grid (N x N): **32, 64, 128, 256, 512**
# * Rozmiar Block (B x B): **2, 4, 8, 16, 32**
#
#----
## Wyniki

#%%[markdown]
#### Zaagregowane wyniki dla ```type=texture```
#%%
by_type[0].describe()

#%%[markdown]
#### Zaagregowane wyniki dla ```type=global```
#%%
by_type[1].describe()

#%%[markdown]
#### Zaagregowane wyniki dla ```type=shared```
#%%
by_type[2].describe()

#%%[markdown]
#### Wpływ typu pamięci na wydajność - wykres łączony
#%%
showParametrized(data=df, x="grid", y="time", hue="type", palette="plasma", ticks=grids, title="Grid v Time", xax='Grid', yax="Time [s]")

#%%[markdown]
##### Wykres przedstawia wszystkie wyniki, mimo to widać, że najlepsze czasy są dla pamięci tekstur.

#%%[markdown]
#### Wpływ typu pamięci na wydajność, ze względu na rozmiar bloku
#%%
for i,b in enumerate(blocks):
    showParametrized(data=by_block[i], x="grid", y="time", hue="type", palette="plasma", ticks=grids, title="Grid v Time, for block="+str(b), xax='Grid', yax="Time [s]")
    plt.show()

#%%[markdown]
##### Wniosek z poprzedniego wykresu potwierdził się, dodatkowo dla ```block=32``` wydajność dla pamięci globalnej i tekstur jest podobna.
##### Oprócz tego widać, że dopiero dla rozmiaru problemu ```grid=512```, można zaobserwować znaczące różnice w czasie wykonania.

#%%[markdown]
#### Wpływ rozmiaru bloku na czas wykonania, w zależności od typu pamięci
#%%
parameter_impact(data=df, x="grid", y="time", hue="block", col="type", xlabel="Grid", ticks=grids)

#%%[markdown]
##### Dla pamięci globalnej i tekstur najlepsze wyniki są dla ```block=32``` i ```block=16```, dla wspódzielonej tylko ```block=16```.
##### Rozmiary bloku poniżej 8 są znacząco gorsze.

#%%[markdown]
#### Dodatkowe porównanie wydajność GPU i CPU
#%%
showParametrized(data=b32_gpu_cpu, x="grid", y="time", hue="type", palette="plasma", ticks=grids, title="Grid v Time, for block=32", xax='Grid', yax="Time [s]")

#%%[markdown]
##### Ten wykres bardzo dobrze pokazuje kwestię persektwy, nawet dla pamięci współdzielonej GPU jest znacząco szybsze od CPU

#%%[markdown]
#### Wpływ rozmiaru bloku na occupancy
#%%
parameter_impact(data=df_occ, x='grid', y='occupancy', hue='operation', col='type', xlabel='Grid', ticks=[256, 512])

#%%
sns.scatterplot(data=df_occ, x='grid', y='occupancy', hue='type', palette='plasma', s=80)

#%%[markdown]
##### Wykresy pokazują trend, taki że operacja **update** ma trochę lepsze occupancy.
##### Jednak jest to za mało danych, żeby móc wyciągnąć jednoznaczne wnioski.

#%%
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
from collections import Counter
sns.set_style('darkgrid')

#%%
def showLess(data, x, y, title=None, xax=None, yax=None):
    sns.set(rc={'figure.figsize':(12, 8)})
    g = sns.scatterplot(x=x, y=y, data=data, s=80, legend='full')
    plt.title(title)
    plt.show()

def showParametrized(data, x, y, hue, ticks, title, xax, yax, palette):
    sns.set(rc={'figure.figsize':(8, 6)})
    g = sns.scatterplot(x=x, y=y, hue=hue, data=data, palette=palette, s=80, legend='full')
    g.set(xticks=ticks)
    plt.title(title)
    plt.ylabel(yax)
    plt.xlabel(xax)
    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    plt.show()

def show(data, x='CPU', y='SpeedUp', hue='Bucket_CPU',\
        ticks=list(range(1,5)), title=None, xax=None, yax=None):
        showParametrized(data, x, y, hue, ticks, title, xax, yax)

def parameter_impact(data, x, y, hue, col, xlabel, ticks):
    g = sns.FacetGrid(data, col="type", hue=hue, palette='plasma', height=6, aspect=1.2, col_wrap=2)
    g = (g.map(plt.scatter, x, y, s=60, alpha=0.9)\
            .set(xticks=ticks)\
            .set_axis_labels(xlabel, "Time [s]")\
            .add_legend()
            )
    plt.show()

path = 'lab5-gpu/results/times.csv'
df = pd.read_csv(path)
df_cpu = pd.read_csv('lab5-gpu/results/cpu-times.csv')
df_occ = pd.read_csv('lab5-gpu/results/occupancy.csv')
blocks = [2,4,8,16,32]
grids = [32,64,128,256,512]
types = ['texture','global', 'shared']
by_block = [df[df['block']==b] for b in blocks]
by_grid = [df[df['grid']==g] for g in grids]
by_type = [df[df['type']==t] for t in types]
b32_gpu_cpu = pd.concat([by_block[4], df_cpu])

#%%


import numpy as np

import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func

from flask import Flask, jsonify
import datetime as dt
#database set up
engine=create_engine('sqlite:///Resources/hawaii.sqlite')

Base= automap_base()
Base.prepare(engine, reflect=True)
Base.classes.keys()
measurements=Base.classes.measurement
stations=Base.classes.station

#flask set up
app=Flask(__name__)

@app.route("/")
def welcome():
    '''list possible routes possible for consumer'''
    return (
        'Available Routes:
'
        f'/api/v1.0/precipitation
'
        f'/api/v1.0/stations
'
        f'/api/v1.0/tobs
'
        f'Please enter date in this format YYYY-MM-DD
'
        f'/api/v1.0/start_date$end_date
'
        f'/api/v1.0/start_date'
    )

@app.route("/api/v1.0/precipitation")
def precipitation():
    # Create our session (link) from Python to the DB
    session = Session(engine)

    """Return a list of all passenger names"""
    # Query all passengers
    results = session.query(measurements.date, measurements.prcp).\
        filter(measurements.date>=(dt.date(2017,8,23)-dt.timedelta(days=365))).all()

    session.close()

    # Convert list of tuples into normal list
    prcp_date = []
    for date, prcp in results:
        prcp_name={}
        prcp_name['station']=date
        prcp_name['precipitation']=prcp
        prcp_date.append(prcp_name)

    return jsonify(prcp_date)

@app.route("/api/v1.0/stations")
def stat():
    # Create our session (link) from Python to the DB
    session = Session(engine)

    """Return a list of all station names"""
    # Query all stations and names
    results = session.query(stations.station, stations.name).all()

    session.close()

    # Convert list of tuples into normal list
    station_data = []
    for station, name in results:
        stat_name={}
        stat_name['station']=station
        stat_name['name']=name
        station_data.append(stat_name)

    return jsonify(station_data)

@app.route("/api/v1.0/tobs")
def tobs():
    # Create our session (link) from Python to the DB
    session = Session(engine)

    """Return a list of all station names"""
    # Query all
    results = session.query(measurements.date, measurements.tobs).\
        filter(measurements.date>(dt.date(2017,8,23)-dt.timedelta(days=365)))\
            .filter(stations.station =='USC00519281').all()

    session.close()

    # Convert list of tuples to something else
    temp_data = []
    for datet, temperature in results:
        temp_name={}
        temp_name['Date']=datet
        temp_name['Temperature']=temperature
        temp_data.append(temp_name)

    return jsonify(temp_data)

@app.route("/api/v1.0/<start_date>$<end_date>")
def start_2(start_date, end_date):
    # '2017-08-16' formart the date should come
    """Fetch the Justice League character whose real_name matches
       the path variable supplied by the user, or a 404 if not."""
    #connect to database
    session = Session(engine)

    """Return a list of all station names"""
    # Query all
    sel=[func.min(measurements.tobs),
        func.max(measurements.tobs),
        func.avg(measurements.tobs)
        ]
    results = session.query(*sel).\
        filter(measurements.date>str(start_date)).filter(measurements.date<=end_date).all()

    session.close()

        #once we have results
        #make able to be displayed
    start_temp_data = []
    for min, max, avg in results:
        temp_name={}
        temp_name['min']=min
        temp_name['max']=max
        temp_name['avg']=avg
        start_temp_data.append(temp_name)

    return jsonify(start_temp_data)

@app.route("/api/v1.0/<start_date>")
def start_end(start_date):
    # '2017-08-16' formart the date should come
    """Fetch the Justice League character whose real_name matches
       the path variable supplied by the user, or a 404 if not."""
    #connect to database
    session = Session(engine)

    """Return a list of all station names"""
    # Query all
    sel=[func.min(measurements.tobs),
        func.max(measurements.tobs),
        func.avg(measurements.tobs)
        ]
    results = session.query(*sel).\
        filter(measurements.date>str(start_date)).all()

    session.close()

        #once we have results
        #make able to be displayed
    start_temp_data = []
    for min, max, avg in results:
        temp_name={}
        temp_name['min']=min
        temp_name['max']=max
        temp_name['avg']=avg
        start_temp_data.append(temp_name)

    return jsonify(start_temp_data)

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


import matplotlib as mpl
import matplotlib.pyplot as plt

import pandas as pd
import numpy as np
import time
import sys
import json

X=pd.read_csv('routes/comp.csv')
X.dropna(axis = 0, how = 'any', inplace = True)
X.drop('COMPLICATIONS', axis = 1, inplace = True)
X.drop('TREATMENT', axis = 1, inplace = True)
y = X.MODE_OF_DELIVERY

X.BLOOD_GP=X.BLOOD_GP.map({'O-': 0,'O+': 1,'A+': 2,'B+': 3,'AB+': 4,'AB-': 5,'A-': 6,'B-': 7})
X.PREVIOUS_LSCS=X.PREVIOUS_LSCS.map({'Y': 1,'N': 0,})
X.CONTRACTED_PELVIS=X.CONTRACTED_PELVIS.map({'Y': 1,'N': 0,})
X.AMMENORRHOEA=X.AMMENORRHOEA.map({'Y': 1,'N': 0,})
X.VOMITTING=X.VOMITTING.map({'Y': 1,'N': 0,'E': 2})
X.WEAKNESS=X.WEAKNESS.map({'Y': 1,'N': 0,})
X.PAIN_IN_ABDOMEN=X.PAIN_IN_ABDOMEN.map({'Y': 1,'N': 0,})
X.OEDEMA_FEET=X.OEDEMA_FEET.map({'Y': 1,'N': 0,})
X.LETHARGY=X.LETHARGY.map({'Y': 1,'N': 0,})
X.SPOTTING_PV=X.SPOTTING_PV.map({'Y': 1,'N': 0,})
X.HEADACHE=X.HEADACHE.map({'Y': 1,'N': 0,})
X.LEG_CRAMPS=X.LEG_CRAMPS.map({'Y': 1,'N': 0,})
X.BURNING_IN_MICTURATION=X.BURNING_IN_MICTURATION.map({'Y': 1,'N': 0,})
X.PEDAL_AND_ABDOMINAL_WALL_OEDEMA=X.PEDAL_AND_ABDOMINAL_WALL_OEDEMA.map({'Y': 1,'N': 0,})
X.HISTORY_OF_GESTATIONAL_DM=X.HISTORY_OF_GESTATIONAL_DM.map({'Y': 1,'N': 0,})
X.HISTORY_OF_HYPERTENSION=X.HISTORY_OF_HYPERTENSION.map({'Y': 1,'N': 0,})
X.EXCESSIVE_WEIGHT_GAIN=X.EXCESSIVE_WEIGHT_GAIN.map({'Y': 1,'N': 0,})
X.FEVER_WITH_COLD_AND_COUGH=X.FEVER_WITH_COLD_AND_COUGH.map({'Y': 1,'N': 0,})
X.LEAKING_PV=X.LEAKING_PV.map({'Y': 1,'N': 0,})
X.URINE=X.URINE.map({'NAD': 0,'PROTEIN+': 1,'PROTEIN++': 2,'PROTEIN+++': 3,'PROTEIN++++': 4,'KETONES+': 5,'KETONES++': 6,'KETONES+++': 7,'KETONES++++': 8,'KETONES_NIL': 9,'ALBUMIN++': 10,'BACTERIA+':11})
X.LIE=X.LIE.map({'N': 0,'T': 1,'O': 2})
X.AMNIOTIC_FLUID=X.AMNIOTIC_FLUID.map({'H': 2,'L': 1,'N': 0,})

X.dropna(axis = 0, how = 'any', inplace = True)
y = X.MODE_OF_DELIVERY
y = y.map({'FTND':0, 'PTND':1, 'LSCS':2,'FTCS':3})
X.drop('MODE_OF_DELIVERY', axis = 1, inplace = True)
y.fillna(0, inplace = True)

#from sklearn.model_selection import train_test_split
#X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 7)

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=20)
model.fit(X,y)

#print model.oob_score_
#score = model.score(X_test, y_test)

#print(score*100)

lines = sys.stdin.readlines()

Z = json.loads(lines[0])

W = np.array(Z)
if(model.predict(W.reshape(1,-1))== 0):
	print("FULL TERM NORMAL DELIVERY")
elif(model.predict(W.reshape(1,-1))== 1):
	print("PRE TERM NORMAL DELIVERY")
elif(model.predict(W.reshape(1,-1))== 2):
	print("LOWER SECTION CESERIAN SECTION")
elif(model.predict(W.reshape(1,-1))== 3):
	print("FULL TERM CESERIAN SECTION")


from dotenv import load_dotenv
load_dotenv()
import utils
from src.server import keep_alive
from src.memory import Memory
from src.models import OpenAIModel
from src.chatgpt import ChatGPT, DALLE
from src.logger import logger
from src.discordBot import DiscordClient, Sender
from typing import Optional
from datetime import datetime
import asyncio
import random
import discord
from discord.ext import tasks
import os
from plugins import error_debugger
from plugins import gpt_llama_cpp
from plugins import deez_nuts
from plugins import chatbot
from plugins import reddit_bot
from plugins import google
from plugins import web
from plugins import pygmalion
from plugins import social_agi

bot_name = os.getenv('BOT_NAME')
model_name = os.getenv('MODEL_NAME')

models = OpenAIModel(api_key=os.getenv('OPENAI_API'),
                     model_engine=os.getenv('OPENAI_MODEL_ENGINE'))

memory = Memory(system_message=os.getenv('SYSTEM_MESSAGE'))
chatgpt = ChatGPT(models, memory)
dalle = DALLE(models)

def run():
    client = DiscordClient()
    sender = Sender()

    # Utils
    async def use_plugin(
        user,
        channel,
        input,
        prompt,
        request_message=None,  # User's original message
        response_type: Optional[str] = 'completion',  # 'completion' or 'chat'
        show_prompt: Optional[bool] = False,
        require_request_message: Optional[bool] = True,
        response_prefix: Optional[str] = '',
        **kwargs
    ):
        async with channel.typing():
            if user == client.user:
                return

            await client.request_queued()
            if require_request_message and request_message is None:
                preprompt = f"🤖\n> _**Prompt:** {prompt}_\n > \n" if show_prompt else '🤖\n'
                request_message = await sender.send_message(f'{preprompt}> <@{user.id}>: _{input}_', channel, **kwargs)

            if response_type == 'chat':
                receive = await chatgpt.get_response_with_system(user, prompt, input,  **kwargs)
            else:
                receive = await chatgpt.get_text_completion(prompt, **kwargs)

        if require_request_message:
            await sender.reply_message(request_message, response_prefix + receive)
        else:
            await sender.send_message(response_prefix + receive, channel)
        await client.request_done()

    # Commands available via "/""
    @ client.tree.command(name="chat", description=f'Chat with {bot_name}')
    async def chat(interaction: discord.Interaction, *, message: str, temperature: Optional[str] = None):
        await interaction.response.defer()
        await interaction.delete_original_response()

        prompt = chatbot.get_prompt(bot_name)
        await use_plugin(interaction.user, interaction.channel, message, prompt, response_type='chat', temperature=temperature)

    @ client.tree.command(name="chat_pro", description="Have a custom chat with a system message")
    async def chat_pro_cmd(interaction: discord.Interaction, *, system_message: str, message: str, think: Optional[str] = None, temperature: Optional[str] = None):
        await interaction.response.defer()
        await interaction.delete_original_response()

        chatgpt.update_api_key(
            '../llama.cpp/models/vicuna/7B/ggml-vicuna-7b-4bit-rev1.bin')
        await use_plugin(interaction.user, interaction.channel, message, system_message, response_type='chat', think=think, show_prompt=True, temperature=temperature)
        chatgpt.reset_api_key()

    @ client.tree.command(name="autocomplete", description="Autocomplete your sentence")
    async def autocomplete_cmd(interaction: discord.Interaction, *, prompt: str, stop_on: Optional[str] = None, same_line: bool = False):
        await interaction.response.defer()
        await interaction.delete_original_response()
        await use_plugin(interaction.user, interaction.channel, prompt, prompt, stop=stop_on, same_line=same_line)

    @ client.tree.command(name="ask", description=f"Ask {bot_name} about gpt-llama.cpp ")
    async def ask_cmd(interaction: discord.Interaction, *, question: str):
        await interaction.response.defer()
        await interaction.delete_original_response()

        prompt = gpt_llama_cpp.get_prompt(question, bot_name)
        await use_plugin(interaction.user, interaction.channel, question, prompt, response_type="completion", stop='\n\n', same_line=True)

    @ client.tree.command(name="reddit", description=f"talk about top news of a subreddit")
    async def reddit_cmd(interaction: discord.Interaction, *, subreddit: str):
        await interaction.response.defer()
        await interaction.delete_original_response()

        prompt = reddit_bot.get_prompt(subreddit, interaction.user.name)
        await use_plugin(interaction.user, interaction.channel, subreddit, prompt, response_type="completion", stop='\n\n\n', same_line=True)

    @ client.tree.command(name="google", description=f"google something")
    async def google_cmd(interaction: discord.Interaction, *, question: str):
        await interaction.response.defer()
        await interaction.delete_original_response()

        prompt = google.get_prompt(question)
        await use_plugin(interaction.user, interaction.channel, question, prompt, response_type="completion", stop='\n\n', same_line=True)

    @ client.tree.command(name="ask_website", description=f"get answers based on a source website")
    async def web_ask_cmd(interaction: discord.Interaction, *, url: str, question: str):
        await interaction.response.defer()
        await interaction.delete_original_response()

        prompt = web.get_prompt(url, question)
        await use_plugin(interaction.user, interaction.channel, question, prompt, response_type="completion", stop='\n\n', same_line=True)

    @ client.tree.command(name="debug", description="Debug your error log")
    async def debug_cmd(interaction: discord.Interaction, *, error_message: str):
        await interaction.response.defer()
        await interaction.delete_original_response()
        prompt = error_debugger.get_prompt(error_message)
        await use_plugin(interaction.user, interaction.channel, error_message, prompt, stop='\n\n')

    @ client.tree.command(name="roleplay", description="Roleplay conversation")
    async def rp_cmd(interaction: discord.Interaction, *, character_name: str, persona: str, scenario: str, message: str):
        await interaction.response.defer()
        await interaction.delete_original_response()

        chatgpt.update_api_key(
            '../llama.cpp/models/pygmalion/7B/ggml-model-q5_1.bin')
        prompt = pygmalion.get_prompt(character_name, persona, scenario, message)
        await use_plugin(interaction.user, interaction.channel, message, prompt, temperature=0.95, stop=['You:'])
        chatgpt.reset_api_key()

    # CREATE A DISCORD BOT THAT JOINS CONVERSATIONS RANDOMLY
    @ client.event
    async def on_message(message):
        channel = message.channel

        blacklist = set(['announcements', 'rules', 'changelog', 'help-forum', 'sentient-bots'])
        graylist = set(['bot-spam'])

        # 0.1 = 10% chance of responding if not directly mentioning the bot
        response_probability = 0.05

        # don't react to system message or unreadable messages
        if message.content == '':
            return

        # don't react to your own messages
        if message.author == client.user:
            return

        # don't message in blacklisted channels
        if channel.name in blacklist:
            return

        # respond if addressed
        # if not addressed only respond to 10% of the messages
        r = random.random()
        message.type == "Message"

        bot_mentioned = bot_name.lower() in message.content.lower(
        ) or f'<@{client.user.id}>' in message.content
        is_reply_to_bot = message.reference is not None and message.reference.resolved.author == client.user
        is_graylist = channel.name in graylist

        # if not addressed (always reply when addressed)
        if not (bot_mentioned or is_reply_to_bot):
            # if channel is in graylist, never respond if not mentioned
            if is_graylist:
                return

            # respond randomly to only 'response_probability' of messages
            if r > response_probability:
                return

        print(f'{bot_name} auto-generating a message...')

        # Get last 30 messages in the channel
        messages = [message async for message in channel.history(limit=20)]
        message_history = []

        # Just get the last 20 before the current message
        for i, msg in enumerate(messages):
            if msg.id == message.id:
                message_history = messages[i: i+15]
        message_history.reverse()  # they come in reversed order

        # Get authors
        authors_full_list = [message.author for message in message_history]
        authors_name_to_id, authors_id_to_name = utils.create_id_name_hashmaps(
            authors_full_list)

        authors = [
            message.author.name for message in message_history if message.author.name != bot_name]
        authors = list(set(authors))  # get unique set of authors
        author_names = ", ".join(authors)

        # Replace author bot_name with 'You' for the prompt
        # Replace bot responses (starting with 🤖) with "Bot" author. This is so we don't confuse "you" with being the bot
        message_history_str = "\n\n".join(
            f"{'DISCORD BOT' if m.content.startswith('🤖') else f'You ({bot_name})' if m.author.name == bot_name else m.author.name} [{m.created_at.strftime('%H:%M:%S %m-%d-%Y')}]:\n{utils.replace_string(m.content, authors_id_to_name)}" for m in message_history)

        prompt = f"""You, {author_names} are users on a public #{message.channel.name} channel of a discord server. You are {bot_name}, an active and fun discord member of the server who's good at coding and is very interested in the recent ai text generation improvements. Each message is formatted in a "<NAME> [DATE]: <MESSAGE>" format, and you guys refer to each other with "@NAME". {bot_name} seems to be very capable at coding and answering questions despite being just human. You guys are having a fun, non-repetitive conversation:

{message_history_str}

You ({bot_name}) [{datetime.now().strftime('%H:%M:%S %m-%d-%Y')}]:"""
        res_message = None
        async with channel.typing():
            await client.request_queued()

            response = await chatgpt.get_text_completion_stream(prompt, '\n\n')
            receive = ''
            queued_chunks = 0
            max_queue_chunks = 7

            async for chunk in response:
                if chunk['choices'][0]['finish_reason']:
                    # response with :no_mouth: if the response failed
                    receive = ':no_mouth:' if len(receive) == 0 else receive
                    break

                curr_chunk = chunk['choices'][0]['delta']['content']
                receive = receive + curr_chunk
                queued_chunks += 1

                if queued_chunks > max_queue_chunks:
                    queued_chunks = 0
                    if len(receive) > 0:
                        res_message = await sender.send_human_message_stream(receive, res_message, channel)

        # send the final message
        await client.request_done()
        await sender.send_human_message_stream(utils.replace_string(receive, authors_name_to_id).lower(), res_message, channel)

    # @ client.tree.command(name="reset", description="Reset ChatGPT conversation history")
    # async def reset(interaction: discord.Interaction):
    #     user_id = interaction.user.id
    #     logger.info(f"resetting memory from {user_id}")
    #     try:
    #         await interaction.response.defer(ephemeral=True)
    #         chatgpt.clean_history(user_id)
    #         await interaction.followup.send(f'> Reset ChatGPT conversation history < - <@{user_id}>')
    #     except Exception as e:
    #         logger.error(f"Error resetting memory: {e}")
    #         await interaction.followup.send('> Oops! Something went wrong. <')

    # REACTION PLUGINS
    @ client.event
    async def on_reaction_add(reaction, user):
        message = reaction.message
        content = message.content  # username: user.name
        channel = message.channel

        # Max only 1 reply per reaction
        if reaction.count > 1:
            return

        if reaction.emoji == '🦙':
            prompt = gpt_llama_cpp.get_prompt(content, bot_name)
            await use_plugin(message.author, channel, content, prompt, request_message=message, response_type="completion", stop='\n\n', same_line=True)
        elif reaction.emoji == '➕':
            await use_plugin(message.author, channel, message, content, request_message=message)
        elif reaction.emoji == '🐞':
            prompt = error_debugger.get_prompt(content)
            await use_plugin(message.author, channel, content, prompt, request_message=message)
        elif reaction.emoji == '🥜':
            prompt = deez_nuts.get_prompt(content)
            await use_plugin(message.author, channel, content, prompt, request_message=message, temperature=1)

    # TASK LOOPS
    @tasks.loop(seconds=60)
    # sentient bots channel id 1103394781041786980

    async def reddit_updates():
        return
        response_probability = 1
        r = random.random()
        if r > response_probability:
            print('Skipping sending sentient message')
            return

        print('Sending sentient message')
        chatgpt.update_api_key('../llama.cpp/models/pygmalion/7B/ggml-model-q5_1.bin')
        channel = await client.fetch_channel(1103394781041786980)
        user = await client.fetch_user(184534707000573952)
        messages = [message async for message in channel.history(limit=2)]
        response_author = messages[1].content.split(': ')[0]
        prompt = await social_agi.get_prompt('ELIZA', 'ALICE', response_author, channel)

        await use_plugin(user, channel, None, prompt, require_request_message=False, temperature=0.9, top_p=1.3, same_line=True, stop='\n', response_prefix=f"{response_author}: ")
        chatgpt.reset_api_key()
        return
        # print('## SEARCHING AND POSTING REDDIT UPDATES')
        # subreddit_list = ['localllama', 'machinelearning', 'chatgpt', 'pygmalionai', 'openai']
        # subreddit = random.choice(subreddit_list)
        # prompt = reddit_bot.get_prompt(subreddit, bot_name)
        # channel = await client.fetch_channel(1099452096383832155)
        # user = await client.fetch_user(184534707000573952)
        # request_message = await sender.send_message(f'**Time to check out `r/{subreddit}` for news!**', channel)
        # await use_plugin(user, channel, subreddit, prompt, response_type="completion", request_message=request_message, stop='\n\n\n', same_line=True)

    # On bot ready
    @client.event
    async def on_ready():
        reddit_updates.start()
        await client.sync()
        print("Bot ready.")

    client.run(os.getenv('DISCORD_TOKEN'))

if __name__ == '__main__':
    keep_alive()
    run()


import uno
import unohelper
from com.sun.star.awt import MessageBoxButtons as MSG_BUTTONS
from com.sun.star.awt.MessageBoxResults import YES
from com.sun.star.awt import Rectangle, Size, Point
from com.sun.star.awt.PosSize import POSSIZE, SIZE
from com.sun.star.beans import PropertyValue, NamedValue
from pathlib import Path
import platform
import getpass
import os
import sys
import re
from typing import Any, Union

CTX = uno.getComponentContext()
SM = CTX.getServiceManager()

def create_instance(name: str, with_context: bool=False, args: Any=None) -> Any:
    if with_context:
        instance = SM.createInstanceWithContext(name, CTX)
    elif args:
        instance = SM.createInstanceWithArguments(name, (args,))
    else:
        instance = SM.createInstance(name)
    return instance

def get_app_config(node_name: str, key: str=''):
    name = 'com.sun.star.configuration.ConfigurationProvider'
    service = 'com.sun.star.configuration.ConfigurationAccess'
    cp = create_instance(name, True)
    node = PropertyValue(Name='nodepath', Value=node_name)
    try:
        ca = cp.createInstanceWithArguments(service, (node,))
        if ca and not key:
            return ca
        if ca and ca.hasByName(key):
            return ca.getPropertyValue(key)
    except Exception as e:
        return ''

NAME = TITLE = get_app_config('org.openoffice.Setup/Product', 'ooName')
DIR = {
    'images': 'images',
    'locales': 'locales',
}

def _set_properties(model, properties):
    if 'X' in properties:
        properties['PositionX'] = properties.pop('X')
    if 'Y' in properties:
        properties['PositionY'] = properties.pop('Y')
    keys = tuple(properties.keys())
    values = tuple(properties.values())
    model.setPropertyValues(keys, values)
    return

class UnoBaseObject(object):

    def __init__(self, obj, path=''):
        self._obj = obj
        self._model = obj.Model

    def __setattr__(self, name, value):
        exists = hasattr(self, name)
        if not exists and not name in ('_obj', '_model'):
            setattr(self._model, name, value)
        else:
            super().__setattr__(name, value)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        pass

    @property
    def obj(self):
        return self._obj

    @property
    def model(self):
        return self._model
    @property
    def m(self):
        return self._model

    @property
    def properties(self):
        return {}
    @properties.setter
    def properties(self, values):
        _set_properties(self.model, values)

    @property
    def name(self):
        return self.model.Name

    @property
    def parent(self):
        return self.obj.Context

    @property
    def tag(self):
        return self.model.Tag
    @tag.setter
    def tag(self, value):
        self.model.Tag = value

    @property
    def visible(self):
        return self.obj.Visible
    @visible.setter
    def visible(self, value):
        self.obj.setVisible(value)

    @property
    def enabled(self):
        return self.model.Enabled
    @enabled.setter
    def enabled(self, value):
        self.model.Enabled = value

    @property
    def step(self):
        return self.model.Step
    @step.setter
    def step(self, value):
        self.model.Step = value

    @property
    def align(self):
        return self.model.Align
    @align.setter
    def align(self, value):
        self.model.Align = value

    @property
    def valign(self):
        return self.model.VerticalAlign
    @valign.setter
    def valign(self, value):
        self.model.VerticalAlign = value

    @property
    def font_weight(self):
        return self.model.FontWeight
    @font_weight.setter
    def font_weight(self, value):
        self.model.FontWeight = value

    @property
    def font_height(self):
        return self.model.FontHeight
    @font_height.setter
    def font_height(self, value):
        self.model.FontHeight = value

    @property
    def font_name(self):
        return self.model.FontName
    @font_name.setter
    def font_name(self, value):
        self.model.FontName = value

    @property
    def font_underline(self):
        return self.model.FontUnderline
    @font_underline.setter
    def font_underline(self, value):
        self.model.FontUnderline = value

    @property
    def text_color(self):
        return self.model.TextColor
    @text_color.setter
    def text_color(self, value):
        self.model.TextColor = value

    @property
    def back_color(self):
        return self.model.BackgroundColor
    @back_color.setter
    def back_color(self, value):
        self.model.BackgroundColor = value

    @property
    def multi_line(self):
        return self.model.MultiLine
    @multi_line.setter
    def multi_line(self, value):
        self.model.MultiLine = value

    @property
    def help_text(self):
        return self.model.HelpText
    @help_text.setter
    def help_text(self, value):
        self.model.HelpText = value

    @property
    def border(self):
        return self.model.Border
    @border.setter
    def border(self, value):
        # ~ Bug for report
        self.model.Border = value

    @property
    def width(self):
        return self._model.Width
    @width.setter
    def width(self, value):
        self.model.Width = value

    @property
    def height(self):
        return self.model.Height
    @height.setter
    def height(self, value):
        self.model.Height = value

    def _get_possize(self, name):
        ps = self.obj.getPosSize()
        return getattr(ps, name)

    def _set_possize(self, name, value):
        ps = self.obj.getPosSize()
        setattr(ps, name, value)
        self.obj.setPosSize(ps.X, ps.Y, ps.Width, ps.Height, POSSIZE)
        return

    @property
    def x(self):
        if hasattr(self.model, 'PositionX'):
            return self.model.PositionX
        return self._get_possize('X')
    @x.setter
    def x(self, value):
        if hasattr(self.model, 'PositionX'):
            self.model.PositionX = value
        else:
            self._set_possize('X', value)

    @property
    def y(self):
        if hasattr(self.model, 'PositionY'):
            return self.model.PositionY
        return self._get_possize('Y')
    @y.setter
    def y(self, value):
        if hasattr(self.model, 'PositionY'):
            self.model.PositionY = value
        else:
            self._set_possize('Y', value)

    @property
    def tab_index(self):
        return self._model.TabIndex
    @tab_index.setter
    def tab_index(self, value):
        self.model.TabIndex = value

    @property
    def tab_stop(self):
        return self._model.Tabstop
    @tab_stop.setter
    def tab_stop(self, value):
        self.model.Tabstop = value

    @property
    def ps(self):
        ps = self.obj.getPosSize()
        return ps
    @ps.setter
    def ps(self, ps):
        self.obj.setPosSize(ps.X, ps.Y, ps.Width, ps.Height, POSSIZE)

    def set_focus(self):
        self.obj.setFocus()
        return

    def ps_from(self, source):
        self.ps = source.ps
        return

    def center(self, horizontal=True, vertical=False):
        p = self.parent.Model
        w = p.Width
        h = p.Height
        if horizontal:
            x = w / 2 - self.width / 2
            self.x = x
        if vertical:
            y = h / 2 - self.height / 2
            self.y = y
        return

    def move(self, origin, x=0, y=5, center=False):
        if x:
            self.x = origin.x + origin.width + x
        else:
            self.x = origin.x
        if y:
            self.y = origin.y + origin.height + y
        else:
            self.y = origin.y

        if center:
            self.center()
        return

# класс компонета label
class UnoLabel(UnoBaseObject):

    def __init__(self, obj):
        super().__init__(obj)

    @property
    def type(self):
        return 'label'

    @property
    def value(self):
        return self.model.Label
    @value.setter
    def value(self, value):
        self.model.Label = value

# класс компонета link
class UnoLabelLink(UnoLabel):

    def __init__(self, obj):
        super().__init__(obj)

    @property
    def type(self):
        return 'link'

# класс компонета button
class UnoButton(UnoBaseObject):

    def __init__(self, obj):
        super().__init__(obj)

    @property
    def type(self):
        return 'button'

    @property
    def value(self):
        return self.model.Label
    @value.setter
    def value(self, value):
        self.model.Label = value

# класс компонета Radio
class UnoRadio(UnoBaseObject):

    def __init__(self, obj):
        super().__init__(obj)

    @property
    def type(self):
        return 'radio'

    @property
    def value(self):
        return self.model.Label
    @value.setter
    def value(self, value):
        self.model.Label = value

# класс компонета checkBox
class UnoCheckBox(UnoBaseObject):

    def __init__(self, obj):
        super().__init__(obj)

    @property
    def type(self):
        return 'checkbox'

    @property
    def value(self):
        return self.model.State
    @value.setter
    def value(self, value):
        self.model.State = value

    @property
    def label(self):
        return self.model.Label
    @label.setter
    def label(self, value):
        self.model.Label = value

    @property
    def tri_state(self):
        return self.model.TriState
    @tri_state.setter
    def tri_state(self, value):
        self.model.TriState = value

# класс компонета text
class UnoText(UnoBaseObject):

    def __init__(self, obj):
        super().__init__(obj)

    @property
    def type(self):
        return 'text'

    @property
    def value(self):
        return self.model.Text
    @value.setter
    def value(self, value):
        self.model.Text = value

    @property
    def echochar(self):
        return chr(self.model.EchoChar)
    @echochar.setter
    def echochar(self, value):
        self.model.EchoChar = ord(value[0])

    def validate(self):
        return

# класс компонета image
class UnoImage(UnoBaseObject):

    def __init__(self, obj):
        super().__init__(obj)

    @property
    def type(self):
        return 'image'

    @property
    def value(self):
        return self.url
    @value.setter
    def value(self, value):
        self.url = value

    @property
    def url(self):
        return self.m.ImageURL
    @url.setter
    def url(self, value):
        self.m.ImageURL = None
        self.m.ImageURL = _P.to_url(value)

# класс компонета listBox
class UnoListBox(UnoBaseObject):

    def __init__(self, obj):
        super().__init__(obj)
        self._path = ''

    def __setattr__(self, name, value):
        if name in ('_path',):
            self.__dict__[name] = value
        else:
            super().__setattr__(name, value)

    @property
    def type(self):
        return 'listbox'

    @property
    def value(self):
        return self.obj.getSelectedItem()

    @property
    def count(self):
        return len(self.data)

    @property
    def data(self):
        return self.model.StringItemList
    @data.setter
    def data(self, values):
        self.model.StringItemList = list(sorted(values))

    @property
    def path(self):
        return self._path
    @path.setter
    def path(self, value):
        self._path = value

    def unselect(self):
        self.obj.selectItem(self.value, False)
        return

    def select(self, pos=0):
        if isinstance(pos, str):
            self.obj.selectItem(pos, True)
        else:
            self.obj.selectItemPos(pos, True)
        return

    def clear(self):
        self.model.removeAllItems()
        return

    def _set_image_url(self, image):
        if _P.exists(image):
            return _P.to_url(image)

        path = _P.join(self._path, DIR['images'], image)
        return _P.to_url(path)

    def insert(self, value, path='', pos=-1, show=True):
        if pos < 0:
            pos = self.count
        if path:
            self.model.insertItem(pos, value, self._set_image_url(path))
        else:
            self.model.insertItemText(pos, value)
        if show:
            self.select(pos)
        return

UNO_CLASSES = {
    'label': UnoLabel,
    'link': UnoLabelLink,
    'button': UnoButton,
    'radio': UnoRadio,
    'checkbox': UnoCheckBox,
    'text': UnoText,
    'image': UnoImage,
    'listbox': UnoListBox,
}

def msgbox(message, title=TITLE, buttons=MSG_BUTTONS.BUTTONS_OK, type_msg='infobox'):
    """ Create message box
        type_msg: infobox, warningbox, errorbox, querybox, messbox
        http://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1awt_1_1XMessageBoxFactory.html
    """
    toolkit = create_instance('com.sun.star.awt.Toolkit')
    parent = toolkit.getDesktopWindow()
    box = toolkit.createMessageBox(parent, type_msg, buttons, title, str(message))
    return box.execute()

def question(message, title=TITLE):
    result = msgbox(message, title, MSG_BUTTONS.BUTTONS_YES_NO, 'querybox')
    return result == YES

def warning(message, title=TITLE):
    return msgbox(message, title, type_msg='warningbox')

def errorbox(message, title=TITLE):
    return msgbox(message, title, type_msg='errorbox')

# класс пользовательской формы
class LODialog(object):
    SEPARATION = 5
    MODELS = {
        'label': 'com.sun.star.awt.UnoControlFixedTextModel',
        'link': 'com.sun.star.awt.UnoControlFixedHyperlinkModel',
        'button': 'com.sun.star.awt.UnoControlButtonModel',
        'radio': 'com.sun.star.awt.UnoControlRadioButtonModel',
        'checkbox': 'com.sun.star.awt.UnoControlCheckBoxModel',
        'text': 'com.sun.star.awt.UnoControlEditModel',
        'image': 'com.sun.star.awt.UnoControlImageControlModel',
        'listbox': 'com.sun.star.awt.UnoControlListBoxModel',
        'groupbox': 'com.sun.star.awt.UnoControlGroupBoxModel',
        'combobox': 'com.sun.star.awt.UnoControlComboBoxModel',
    }

    # конструткор класса
    def __init__(self, args):
        self._obj = self._create(args)
        self._model = self.obj.Model
        self._events = None
        self._modal = True
        self._controls = {}
        self._color_on_focus = COLOR_ON_FOCUS
        self._id = ''
        self._path = ''
        self._init_controls()

    # создание формы
    def _create(self, args):
        service = 'com.sun.star.awt.DialogProvider'
        path = args.pop('Path', '')
        if path:
            dp = create_instance(service, True)
            dlg = dp.createDialog(_P.to_url(path))
            return dlg

        if 'Location' in args:
            name = args['Name']
            library = args.get('Library', 'Standard')
            location = args.get('Location', 'application').lower()
            if location == 'user':
                location = 'application'
            url = f'vnd.sun.star.script:{library}.{name}?location={location}'
            if location == 'document':
                dp = create_instance(service, args=docs.active.obj)
            else:
                dp = create_instance(service, True)

            dlg = dp.createDialog(url)
            return dlg

        dlg = create_instance('com.sun.star.awt.UnoControlDialog', True)
        model = create_instance('com.sun.star.awt.UnoControlDialogModel', True)
        toolkit = create_instance('com.sun.star.awt.Toolkit', True)
        _set_properties(model, args)
        dlg.setModel(model)
        dlg.setVisible(False)
        dlg.createPeer(toolkit, None)
        return dlg

    # получение типа компонента
    def _get_type_control(self, name):
        name = name.split('.')[2]
        types = {
            'UnoFixedTextControl': 'label',
            'UnoEditControl': 'text',
            'UnoButtonControl': 'button',
        }
        return types[name]

    # инициализация компонента
    def _init_controls(self):
        for control in self.obj.getControls():
            tipo = self._get_type_control(control.ImplementationName)
            name = control.Model.Name
            control = UNO_CLASSES[tipo](control)
            setattr(self, name, control)
        return

    @property
    def obj(self):
        return self._obj

    @property
    def model(self):
        return self._model

    @property
    def controls(self):
        return self._controls

    @property
    def path(self):
        return self._path
    @property
    def id(self):
        return self._id

    @property
    def height(self):
        return self.model.Height
    @height.setter
    def height(self, value):
        self.model.Height = value

    @property
    def width(self):
        return self.model.Width
    @width.setter
    def width(self, value):
        self.model.Width = value

    @property
    def visible(self):
        return self.obj.Visible
    @visible.setter
    def visible(self, value):
        self.obj.Visible = value

    @property
    def step(self):
        return self.model.Step
    @step.setter
    def step(self, value):
        self.model.Step = value

    @property
    def events(self):
        return self._events
    @events.setter
    def events(self, controllers):
        self._events = controllers(self)
        self._connect_listeners()

    @property
    def color_on_focus(self):
        return self._color_on_focus
    @color_on_focus.setter
    def color_on_focus(self, value):
        self._color_on_focus = get_color(value)

    def _special_properties(self, tipo, args):
        if tipo == 'link' and not 'Label' in args:
            args['Label'] = args['URL']
            return args

        if tipo == 'button':
            if 'ImageURL' in args:
                args['ImageURL'] = self._set_image_url(args['ImageURL'])
            args['FocusOnClick'] = args.get('FocusOnClick', False)
            return args

        return args

    # добавление компонента
    def add_control(self, args):
        tipo = args.pop('Type').lower()

        args = self._special_properties(tipo, args)
        model = self.model.createInstance(self.MODELS[tipo])
        _set_properties(model, args)
        name = args['Name']
        self.model.insertByName(name, model)
        control = self.obj.getControl(name)
        control = UNO_CLASSES[tipo](control)

        if tipo in ('listbox',):
            control.path = self.path

        setattr(self, name, control)
        self._controls[name] = control
        control = self.obj.getControl(name)
        return control

    # центрирования компонента
    def center(self, control, x=0, y=0):
        w = self.width
        h = self.height

        if isinstance(control, tuple):
            wt = self.SEPARATION * -1
            for c in control:
                wt += c.width + self.SEPARATION
            x = w / 2 - wt / 2
            for c in control:
                c.x = x
                x = c.x + c.width + self.SEPARATION
            return

        if x < 0:
            x = w + x - control.width
        elif x == 0:
            x = w / 2 - control.width / 2
        if y < 0:
            y = h + y - control.height
        elif y == 0:
            y = h / 2 - control.height / 2
        control.x = x
        control.y = y
        return

    # открытие формы
    def open(self, modal=True):
        self._modal = modal
        if modal:
            return self.obj.execute()
        else:
            self.visible = True
        return

    # закрытие формы
    def close(self, value=0):
        if self._modal:
            value = self.obj.endDialog(value)
        else:
            self.visible = False
            self.obj.dispose()
        return value

    def set_values(self, data):
        for k, v in data.items():
            self._controls[k].value = v
        return

def create_dialog(args):
    return LODialog(args)

class Paths(object):
    FILE_PICKER = 'com.sun.star.ui.dialogs.FilePicker'
    FOLDER_PICKER = 'com.sun.star.ui.dialogs.FolderPicker'

    def __init__(self, path=''):
        if path.startswith('file://'):
            path = str(Path(uno.fileUrlToSystemPath(path)).resolve())
        self._path = Path(path)

    @classmethod
    def to_url(cls, path):
        if not path.startswith('file://'):
            path = Path(path).as_uri()
        return path

_P = Paths
# ~ https://en.wikipedia.org/wiki/Web_colors
def get_color(value):
    COLORS = {
        'aliceblue': 15792383,
        'antiquewhite': 16444375,
        'aqua': 65535,
        'aquamarine': 8388564,
        'azure': 15794175,
        'beige': 16119260,
        'bisque': 16770244,
        'black': 0,
        'blanchedalmond': 16772045,
        'blue': 255,
        'blueviolet': 9055202,
        'brown': 10824234,
        'burlywood': 14596231,
        'cadetblue': 6266528,
        'chartreuse': 8388352,
        'chocolate': 13789470,
        'coral': 16744272,
        'cornflowerblue': 6591981,
        'cornsilk': 16775388,
        'crimson': 14423100,
        'cyan': 65535,
        'darkblue': 139,
        'darkcyan': 35723,
        'darkgoldenrod': 12092939,
        'darkgray': 11119017,
        'darkgreen': 25600,
        'darkgrey': 11119017,
        'darkkhaki': 12433259,
        'darkmagenta': 9109643,
        'darkolivegreen': 5597999,
        'darkorange': 16747520,
        'darkorchid': 10040012,
        'darkred': 9109504,
        'darksalmon': 15308410,
        'darkseagreen': 9419919,
        'darkslateblue': 4734347,
        'darkslategray': 3100495,
        'darkslategrey': 3100495,
        'darkturquoise': 52945,
        'darkviolet': 9699539,
        'deeppink': 16716947,
        'deepskyblue': 49151,
        'dimgray': 6908265,
        'dimgrey': 6908265,
        'dodgerblue': 2003199,
        'firebrick': 11674146,
        'floralwhite': 16775920,
        'forestgreen': 2263842,
        'fuchsia': 16711935,
        'gainsboro': 14474460,
        'ghostwhite': 16316671,
        'gold': 16766720,
        'goldenrod': 14329120,
        'gray': 8421504,
        'grey': 8421504,
        'green': 32768,
        'greenyellow': 11403055,
        'honeydew': 15794160,
        'hotpink': 16738740,
        'indianred': 13458524,
        'indigo': 4915330,
        'ivory': 16777200,
        'khaki': 15787660,
        'lavender': 15132410,
        'lavenderblush': 16773365,
        'lawngreen': 8190976,
        'lemonchiffon': 16775885,
        'lightblue': 11393254,
        'lightcoral': 15761536,
        'lightcyan': 14745599,
        'lightgoldenrodyellow': 16448210,
        'lightgray': 13882323,
        'lightgreen': 9498256,
        'lightgrey': 13882323,
        'lightpink': 16758465,
        'lightsalmon': 16752762,
        'lightseagreen': 2142890,
        'lightskyblue': 8900346,
        'lightslategray': 7833753,
        'lightslategrey': 7833753,
        'lightsteelblue': 11584734,
        'lightyellow': 16777184,
        'lime': 65280,
        'limegreen': 3329330,
        'linen': 16445670,
        'magenta': 16711935,
        'maroon': 8388608,
        'mediumaquamarine': 6737322,
        'mediumblue': 205,
        'mediumorchid': 12211667,
        'mediumpurple': 9662683,
        'mediumseagreen': 3978097,
        'mediumslateblue': 8087790,
        'mediumspringgreen': 64154,
        'mediumturquoise': 4772300,
        'mediumvioletred': 13047173,
        'midnightblue': 1644912,
        'mintcream': 16121850,
        'mistyrose': 16770273,
        'moccasin': 16770229,
        'navajowhite': 16768685,
        'navy': 128,
        'oldlace': 16643558,
        'olive': 8421376,
        'olivedrab': 7048739,
        'orange': 16753920,
        'orangered': 16729344,
        'orchid': 14315734,
        'palegoldenrod': 15657130,
        'palegreen': 10025880,
        'paleturquoise': 11529966,
        'palevioletred': 14381203,
        'papayawhip': 16773077,
        'peachpuff': 16767673,
        'peru': 13468991,
        'pink': 16761035,
        'plum': 14524637,
        'powderblue': 11591910,
        'purple': 8388736,
        'red': 16711680,
        'rosybrown': 12357519,
        'royalblue': 4286945,
        'saddlebrown': 9127187,
        'salmon': 16416882,
        'sandybrown': 16032864,
        'seagreen': 3050327,
        'seashell': 16774638,
        'sienna': 10506797,
        'silver': 12632256,
        'skyblue': 8900331,
        'slateblue': 6970061,
        'slategray': 7372944,
        'slategrey': 7372944,
        'snow': 16775930,
        'springgreen': 65407,
        'steelblue': 4620980,
        'tan': 13808780,
        'teal': 32896,
        'thistle': 14204888,
        'tomato': 16737095,
        'turquoise': 4251856,
        'violet': 15631086,
        'wheat': 16113331,
        'white': 16777215,
        'whitesmoke': 16119285,
        'yellow': 16776960,
        'yellowgreen': 10145074,
    }

    if isinstance(value, tuple):
        color = (value[0] << 16) + (value[1] << 8) + value[2]
    else:
        if value[0] == '#':
            r, g, b = bytes.fromhex(value[1:])
            color = (r << 16) + (g << 8) + b
        else:
            color = COLORS.get(value.lower(), -1)
    return color

COLOR_ON_FOCUS = get_color('LightYellow')


"""Library for checking strings in files."""

##==============================================================#
## DEVELOPED 2015, REVISED 2017, Jeff Rimko.                    #
##==============================================================#

##==============================================================#
## SECTION: Imports                                             #
##==============================================================#

from __future__ import print_function

import copy
import inspect
import os
import os.path as op
from collections import namedtuple

##==============================================================#
## SECTION: Global Definitions                                  #
##==============================================================#

#: Library version string.
__version__ = "0.4.1"

#: Contains information for a single checked item.
VerInfo = namedtuple("VerInfo", "path linenum string")

#: Defines a file check.
VerCheck = namedtuple("VerCheck", "path func opts updatable")

##==============================================================#
## SECTION: Class Definitions                                   #
##==============================================================#

class VerChecker(object):
    def __init__(self, name, root):
        """Initializes the checker object.

        **Params**:
          - name (str) - Name associated with items checked.
          - root (str) - Root path used to resolve relative paths for checked
            files. Can be a file or directory."""
        self.name = name
        if op.isfile(root):
            root = op.dirname(root)
        self.root = op.abspath(root)
        self._string = None
        self._checks = []
        self._vinfos = []
        self.debug = False
    def _run_check(self, c):
        """Runs a single VerCheck and returns a list of (VerInfo,updatable)
        tuples."""
        dprint = get_vprint(self.debug)
        # Setup file path.
        path = c.path
        if not op.isabs(path):
            path = op.join(self.root, path)
        path = op.normpath(path)
        # Setup function and function type.
        if type(c.func) in [list, tuple]: func,ftyp = c.func
        else: func,ftyp = (c.func, "file")
        if (not func) or (not hasattr(func, "__call__")):
            func = check_basic
        # Run the function over the file and collect VerInfo objects.
        vinfos = []
        if "file" == ftyp:
            v = func(path, **c.opts)
            dprint((inspect.stack()[0][3], c, v))
            if list != type(v): v = [v]
            vinfos += v
        elif "line" == ftyp:
            for num,line in readlines(path):
                string = func(line, **c.opts)
                if string:
                    vinfos.append(VerInfo(path, num, string))
        self._vinfos += vinfos
        return [(v, c.updatable) for v in vinfos if v]
    def _iter_vinfo(self, get_updatable=False):
        """Iterates over the associated VerInfo objects. Optionally returns if
        the associated file is updatable."""
        vulist = [] # Holds (VerInfo,updatable) items.
        self._vinfos = []
        for c in self._checks:
            vulist += self._run_check(c)
        for vu in sorted(vulist, key=lambda i: (i[0].path, i[0].linenum)):
            if vu:
                yield vu if get_updatable else vu[0]
    def string(self):
        """Returns the string if `run()` found no inconsistencies,
        otherwise None is returned. Always calls `run()`."""
        self.run(False)
        return self._string
    def include(self, path, func=None, opts=None, updatable=True, **kwargs):
        """Includes a file to check.

        **Params**:
          - path (str) - Path to a file to check.
          - func (function|(tuple,str)) - Either a (func,type) tuple or a
            function (type defaults to 'file'). Valid type values are
            'file|line'. The type controls whether the file path or individual
            lines will be passed to the function. A file function may return
            either single VerInfo or a list of VerInfos. A line function may
            return a string.
          - opts (dict) - Options to pass to the check function. Any additional
            keyword args will be included.
          - updatable (bool) - If true, string can be updated using `update()`.
        """
        if not opts:
            opts = {}
        opts.update(copy.deepcopy(kwargs))
        c = VerCheck(path, func, copy.deepcopy(opts), updatable)
        self._checks.append(c)
    def run(self, verbose=True):
        """Runs checks on all included items, reports any inconsistencies.
        Returns string if consistent else None."""
        vprint = get_vprint(verbose)
        strings = []
        vprint(self.name + ":")
        for vinfo in self._iter_vinfo():
            if vinfo.string not in strings:
                strings.append(vinfo.string)
            vprint("  `%s` (%s:%u)" % (
                    vinfo.string,
                    op.relpath(vinfo.path),
                    vinfo.linenum))
        if strings:
            self._string = list(strings)[0] if 1 == len(strings) else None
            if not self._string:
                vprint("[WARNING] Strings differ!")
        else:
            self._string = None
            vprint("[WARNING] No string info found!")
        return self._string
    def update(self, newstr):
        """Updates all associated strings to the given new string. Use
        caution as this will modify file content! Returns number of strings
        updated."""
        updated = 0
        for vinfo,updatable in self._iter_vinfo(get_updatable=True):
            if not updatable:
                continue
            with open(vinfo.path) as fi:
                temp = op.join(
                        op.dirname(vinfo.path),
                        "__temp-verace-" + op.basename(vinfo.path))
                with open(temp, "w") as fo:
                    for num,line in enumerate(fi.readlines(), 1):
                        if num == vinfo.linenum:
                            line = line.replace(vinfo.string, newstr)
                        fo.write(line)
            os.remove(vinfo.path)
            os.rename(temp, vinfo.path)
            updated += 1
        return updated
    def prompt(self):
        """Shows the standard prompt for handling checked strings."""
        try:
            import qprompt
        except:
            print("The `qprompt` library is needed for this functionality!")
            return
        self.run()
        if not self._checks:
            qprompt.pause()
            return
        ns = len(self._vinfos)
        nu = len({v.string for v in self._vinfos})
        nf = len({v.path for v in self._vinfos})
        ss = "string" + ("s" if ns != 1 else "")
        sf = "file" + ("s" if nf != 1 else "")
        msg = "Found %u %s (%u unique) in %u %s." % (
                ns, ss, nu, nf, sf)
        qprompt.alert(msg)
        if qprompt.ask_yesno("Update string?", dft="n"):
            newstr = qprompt.ask_str("New string")
            if newstr:
                self.update(newstr)
                self.prompt()

##==============================================================#
## SECTION: Function Definitions                                #
##==============================================================#

def get_vprint(verbose):
    """Helper function for optional verbose printing."""
    def _vprint(msg, end=None):
        if None != end:
            print(msg, end=end)
        else:
            print(msg)
    def _nprint(msg, endl=True):
        pass
    if verbose:
        return _vprint
    return _nprint

def readlines(fpath):
    """Generator that reads the file at the given path line by line yielding
    (number,text) for each."""
    with open(fpath) as fi:
        for num,line in enumerate(fi.readlines(), 1):
            yield num,line

def check_basic(path, match="version", splits=None, single=True):
    """Basic check function. Iterates through files lines until the `match`
    string is found. The matching line will be split using the list of
    (characters,index) tuples/lists from `splits`. Can either return a single
    (first) result or all results in the file. **NOTE**: `splits` must be a
    list of tuples/lists!"""
    splits = splits or []
    vinfos = []
    for num,line in readlines(path):
        if line.find(match) > -1:
            vstr = line
            for char,indx in splits:
                vstr = vstr.split(char)[indx].strip()
            vinfos.append(VerInfo(path, num, vstr))
    if single and len(vinfos) > 1:
        return vinfos[0]
    return vinfos

##==============================================================#
## SECTION: Main Body                                           #
##==============================================================#

if __name__ == '__main__':
    mychk = VerChecker("My Checker", __file__)
    mychk.include(r"setup.py", match="version = ", splits=[('"', 1)])
    mychk.prompt()


import os
import time
from playsound import playsound
import random
from string import capwords
import speech_recognition as sr
import pyttsx3
from player import Player
from song import Song

class Game():

    '''
    This is game class. Each game that is played is represented by this class.
    '''

    availableLang = ("English", "Hindi")
    availableNoOfQ = (3, 4, 5)
    availableGenres = tuple(os.listdir("Songs"))

    @staticmethod
    def speak(text):
        '''
        This function converts the text into speech(voice) using pyttsx3 module
        '''

        engine = pyttsx3.init()
        print(text)
        engine.say(text)
        engine.runAndWait()

    @staticmethod
    def getAudio():
        '''
        This function gets speech (voice) input from the user and converts it into text using Google's Speech Recognition module.
        '''

        r = sr.Recognizer()
        said = ""

        with sr.Microphone() as source:
            print("Adjusting sound for Ambient Noise...")
            r.adjust_for_ambient_noise(source, duration=1)

            print("Listening...")
            audio = r.listen(source)

            try:
                print("Sending sound to google servers")
                said = r.recognize_google(audio)
                print(said)
            except:
                print("Sorry, Didn't get that one. Let's go again...")
                said = Game.getAudio()

            return said

    def __init__(self):
        pass

    def getLang(self):
        '''
        Getting lang from the user
        '''

        while True:
            text = "These are the list of LANGUAGES you can choose from"
            Game.speak(text)

            for lang in Game.availableLang:
                print(f"{Game.availableLang.index(lang)+1}. {lang}")

            print("Choose Your Language...")
            self.lang = Game.getAudio()

            if self.lang in Game.availableLang:
                break
            else:
                text = "Sorry, This Option is not available. Choose a valid option."
                Game.speak(text)

        return self.lang

    def getGenre(self):
        '''
        Getting Genre from the user
        '''

        while True:
            text = "These are the list of GENRES you can choose from"
            Game.speak(text)

            for genre in Game.availableGenres:
                print(f"{Game.availableGenres.index(genre)+1}. {genre}")

            text = "For example if you want to choose Hip Hop just say, 'Hip Hop'"
            Game.speak(text)

            print("Choose Your Genre...")
            self.genre = Game.getAudio()

            if self.genre in Game.availableGenres:
                break
            else:
                text = "Sorry, This Option is not available. Choose a valid option."
                Game.speak(text)

        return self.genre

    def getNoOfQues(self):
        '''
        Getting number of questions from the user
        '''

        text = "Now, tell me how many questions do you want to answer.\nYou can say 3, 4 or 5"
        Game.speak(text)

        while True:
            print("Choose Number of Questions")
            self.noOfQuestions = Game.getAudio()
            if self.noOfQuestions.isdigit() and int(self.noOfQuestions) in Game.availableNoOfQ:
                self.noOfQuestions = int(self.noOfQuestions)
                break
            else:
                text = "Sorry, This option is not available. Choose a valid option."
                Game.speak(text)

        return self.noOfQuestions

    def generateRandomPlaylist(self):
        '''
        Generating random playlist of the songs for the user
        '''

        self.availableSongs = os.listdir(
            f"Songs\\{self.genre}\\{self.lang}\\")
        randNos = random.sample(
            range(len(self.availableSongs)), self.noOfQuestions)
        self.randomPlaylist = [
            self.availableSongs[x].replace(".mp3", "") for x in randNos]

    def start(self, player):
        '''
        Main function that starts the game
        '''

        QPosition = {
            '1': "first",
            '2': "second",
            '3': "third",
            '4': "fourth",
            '5': "fifth",
            '6': "sixth",
            '7': "seventh"
        }

        QPosition[self.noOfQuestions] = "last"

        self.generateRandomPlaylist()

        for i in range(len(self.randomPlaylist)):
            text = f"Here's the {QPosition[str(i+1)]} song."
            Game.speak(text)

            playsound(
                f"Songs\\{self.genre}\\{self.lang}\\{self.randomPlaylist[i]}.mp3")

            songName = self.randomPlaylist[i].split("-")[0]
            artistName = self.randomPlaylist[i].split("-")[1]
            currSong = Song(songName, artistName)

            print("Your Response: ")

            response = Game.getAudio()

            text = self.chkAns(currSong, response)

            player.updateScore(currSong.getPoints())

            text += f" The song is '{capwords(songName)}' by '{capwords(artistName)}'. You scored {currSong.getPoints()} points on this question. Your current score is '{player.getScore()}'"

            Game.speak(text)

    def chkAns(self, song, response):
        '''
        This function whether user has given the correct answer and award points accordingly.
        '''

        songResponse = ""
        artistResponse = ""

        response = response.split(" by ")

        if len(response) > 1:
            songResponse = response[0].lower()
            artistResponse = response[1].lower()
        else:
            songResponse = response[0].lower()
            artistResponse = response[0].lower()

        if songResponse in song.getName() and artistResponse in song.getArtist():
            song.setPoints(20)
            text = "Wow! You get the song as well as the artist correct. "
        elif songResponse in song.getName():
            song.setPoints(10)
            text = "Great! You get the song correct. "
        elif artistResponse in song.getArtist():
            song.setPoints(10)
            text = "Wonderful! You get the artist correct. "
        else:
            text = "Sorry!"

        return text


from setuptools import setup
from setuptools.command.test import test as TestCommand
import sys
import re
import ast

def _get_version():
    version_re = re.compile(r'__version__\s+=\s+(.*)')

    with open('flask_transfer/__init__.py', 'rb') as fh:
        version = ast.literal_eval(
            version_re.search(fh.read().decode('utf-8')).group(1))

    return str(version)

class ToxTest(TestCommand):
    user_options = [('tox-args=', 'a', 'Arguments to pass to tox')]

    def initialize_options(self):
        TestCommand.initialize_options(self)
        self.tox_args = None

    def finalize_options(self):
        TestCommand.finalize_options(self)
        self.test_args = []
        self.test_suite = True

    def run_tests(self):
        import tox
        import shlex
        args = []
        if self.tox_args:
            args = shlex.split(self.tox_args)

        errno = tox.cmdline(args=args)
        sys.exit(errno)

if __name__ == "__main__":
    setup(
        name='flask-transfer',
        version=_get_version(),
        author='Alec Nikolas Reiter',
        author_email='alecreiter@gmail.com',
        description='Validate and process file uploads in Flask easily',
        license='MIT',
        packages=['flask_transfer'],
        zip_safe=False,
        url="https://github.com/justanr/Flask-Transfer",
        keywords=['flask', 'uploads'],
        classifiers=[
            'Development Status :: 3 - Alpha',
            'Framework :: Flask',
            'Environment :: Web Environment',
            'Intended Audience :: Developers',
            'License :: OSI Approved :: MIT License',
            'Programming Language :: Python :: 2.7',
            'Programming Language :: Python :: 3.4'
        ],
        install_requires=['Flask'],
        test_suite='test',
        tests_require=['tox'],
        cmdclass={'tox': ToxTest},
    )


import random

import cv2
import numpy as np
import torch

from .augmentation import add_occlusion, add_DPG
from ..bbox import bbox_xywh_to_cs, bbox_cs_to_xyxy
from ..camera import get_intrinsic_metrix
from ..transforms import (im_to_torch, affine_transform, get_affine_transform, batch_rodrigues_numpy,
                          flip_joints_vis, flip_xyz_joints_3d, flip_thetas,
                          rotate_xyz_jts, rotate_axis_angle)

class SMPL3DCamWrapper(object):
    def __init__(self, dataset, input_size, output_size, train,
                 scale_factor, color_factor, occlusion, add_dpg, rot, flip,
                 scale_mult=1.25, with_smpl=True, focal_length=1000., root_idx=0):
        """ Data augmentation.
        Occlusion, Truncation(half-body), Scale, Rotation, Flip, Color.
        """

        if not with_smpl:
            self._joint_pairs = dataset.joint_pairs
        else:
            self._joint_pairs_17 = dataset.joint_pairs_17
            self._joint_pairs_24 = dataset.joint_pairs_24
            self._joint_pairs_29 = dataset.joint_pairs_29
            self._joint_pairs_11 = dataset.joint_pairs_11

        self._input_size = input_size
        self._heatmap_size = output_size
        self._train = train

        self._scale_factor = scale_factor
        self._color_factor = color_factor
        self._occlusion = occlusion
        self._add_dpg = add_dpg
        self._rot = rot
        self._flip = flip

        self._scale_mult = scale_mult
        self.with_smpl = with_smpl
        self.focal_length = focal_length
        self.root_idx = root_idx  # ATTN: the root index of mpi_inf is 4 !!!

        self._aspect_ratio = float(input_size[1]) / input_size[0]  # w / h

        self.pixel_std = 1

        self.bbox_3d_shape = dataset.bbox_3d_shape

        if train:
            self.num_joints_half_body = dataset.num_joints_half_body
            self.prob_half_body = dataset.prob_half_body

            self.upper_body_ids = dataset.upper_body_ids
            self.lower_body_ids = dataset.lower_body_ids

    def test_transform(self, src, bbox):
        if isinstance(src, str):
            src = cv2.cvtColor(cv2.imread(src), cv2.COLOR_BGR2RGB)

        xmin, ymin, xmax, ymax = bbox
        center, scale = bbox_xywh_to_cs(
            xmin, ymin, xmax - xmin, ymax - ymin, self._aspect_ratio, scale_mult=self._scale_mult)
        scale = scale * 1.0

        inp_h, inp_w = self._input_size
        trans = get_affine_transform(center, scale, 0, [inp_w, inp_h])

        img = cv2.warpAffine(src, trans, (int(inp_w), int(inp_h)), flags=cv2.INTER_LINEAR)
        bbox = bbox_cs_to_xyxy(center, scale)

        img = im_to_torch(img)
        # mean
        img[0].add_(-0.485)
        img[1].add_(-0.456)
        img[2].add_(-0.406)

        # std
        img[0].div_(0.229)
        img[1].div_(0.224)
        img[2].div_(0.225)

        # img_center = np.array([float(src.shape[1]) * 0.5, float(src.shape[0]) * 0.5])

        return img, bbox

    def _uvd_target_generator(self, joints_3d, num_joints, patch_height, patch_width):
        target_weight = joints_3d[:, :, 1].copy()

        target = np.zeros((num_joints, 3), dtype=np.float32)
        target[:, 0] = joints_3d[:, 0, 0] / patch_width - 0.5
        target[:, 1] = joints_3d[:, 1, 0] / patch_height - 0.5
        target[:, 2] = joints_3d[:, 2, 0] / self.bbox_3d_shape[2]

        target = target.reshape(-1)
        target_weight = target_weight.reshape(-1)
        return target, target_weight

    def _xyz_target_generator(self, joints_3d, joints_3d_vis, num_joints):
        target_weight = joints_3d_vis.copy()

        target = np.zeros((num_joints, 3), dtype=np.float32)
        target[:, 0] = joints_3d[:, 0] / self.bbox_3d_shape[0]
        target[:, 1] = joints_3d[:, 1] / self.bbox_3d_shape[1]
        target[:, 2] = joints_3d[:, 2] / self.bbox_3d_shape[2]

        target = target.reshape(-1)
        target_weight = target_weight.reshape(-1)
        return target, target_weight

    def __call__(self, src, label):
        #============================= Only 3D keypoints =============================#
        if not self.with_smpl:
            bbox = list(label['bbox'])
            imgwidth, imgheight = label['width'], label['height']
            assert imgwidth == src.shape[1] and imgheight == src.shape[0]

            joints_img = label['joint_img'].copy()
            joints_vis = label['joint_vis'].copy()
            joints_cam = label['joint_cam'].copy()

            self.num_joints = joints_img.shape[0]
            gt_joints = np.zeros((self.num_joints, 3, 2), dtype=np.float32)
            gt_joints[:, :, 0] = joints_img
            gt_joints[:, :, 1] = joints_vis

            input_size = self._input_size

            if self._train and self._add_dpg:
                bbox = add_DPG(bbox, imgwidth, imgheight)

            xmin, ymin, xmax, ymax = bbox
            center, scale = bbox_xywh_to_cs(
                xmin, ymin, xmax - xmin, ymax - ymin, self._aspect_ratio, scale_mult=self._scale_mult)
            xmin, ymin, xmax, ymax = bbox_cs_to_xyxy(center, scale)

            #----------------------------- Occlusion -----------------------------#
            if self._train and self._occlusion:
                add_occlusion(src, xmin, xmax, ymin, ymax, imgwidth, imgheight)

            #----------------------------- Half body transform -----------------------------#
            if self._train and (np.sum(joints_vis[:, 0]) > self.num_joints_half_body \
                           and np.random.rand() < self.prob_half_body):

                c_half_body, s_half_body = self.half_body_transform(gt_joints[:, :, 0], joints_vis)
                if c_half_body is not None and s_half_body is not None:
                    center, scale = c_half_body, s_half_body

            #----------------------------- Scale -----------------------------#
            if self._train and self._scale_factor > 0:
                sf = self._scale_factor
                scale = scale * np.clip(np.random.randn() * sf + 1, 1 - sf, 1 + sf)
            else:
                scale = scale * 1.0

            #----------------------------- Rotation -----------------------------#
            if self._train and self._rot > 0:
                rf = self._rot
                r = np.clip(np.random.randn() * rf, -rf * 2, rf * 2) if random.random() <= 0.6 else 0
            else:
                r = 0

            #----------------------------- Flip -----------------------------#
            joints = gt_joints
            joints_cam = joints_cam.reshape(-1 , 3)
            joints_rel = joints_cam - joints_cam[[self.root_idx]] # the root index of mpi_inf is 4 !!!

            if self._train and self._flip and random.random() > 0.5:
                assert src.shape[2] == 3
                src = src[:, ::-1, :]

                joints = flip_joints_vis(joints, imgwidth, self._joint_pairs)
                joints_rel = flip_xyz_joints_3d(joints_rel, self._joint_pairs)
                center[0] = imgwidth - center[0] - 1

            #----------------------------- Transform image -----------------------------#
            inp_h, inp_w = input_size
            trans = get_affine_transform(center, scale, r, [inp_w, inp_h])
            img = cv2.warpAffine(src, trans, (int(inp_w), int(inp_h)), flags=cv2.INTER_LINEAR)
            bbox = bbox_cs_to_xyxy(center, scale)

            #----------------------------- Transform joints -----------------------------#
            # Transform 2D joints
            for i in range(self.num_joints):
                if joints[i, 0, 1] > 0.0:
                    joints[i, 0:2, 0] = affine_transform(joints[i, 0:2, 0], trans)

            # Rotate 3D joints
            joints_rel = rotate_xyz_jts(joints_rel, r)

            #----------------------------- Target generation -----------------------------#
            target_uvd, target_weight = self._uvd_target_generator(joints, self.num_joints, inp_h, inp_w)
            target_xyz, target_xyz_weight = self._xyz_target_generator(joints_rel, joints_vis, self.num_joints)
            target_weight *= joints_vis.reshape(-1)

            #----------------------------- Others -----------------------------#
            trans_inv = get_affine_transform(center, scale, r, [inp_w, inp_h], inv=True).astype(np.float32)

            intrinsic_param = get_intrinsic_metrix(label['f'], label['c']).astype(np.float32) if 'f' in label.keys() \
                else np.array([[self.focal_length, 0., imgwidth*0.5],
                               [0., self.focal_length, imgheight*0.5],
                               [0., 0., 1.]]).astype(np.float32)

            joint_root = 0.001 * label['root_cam'].astype(np.float32) if 'root_cam' in label.keys() \
                else np.array([0., 0., 3.]).astype(np.float32)

        #============================= With SMPL annotations =============================#
        else:
            bbox = list(label['bbox'])
            imgwidth, imgheight = label['width'], label['height']
            assert imgwidth == src.shape[1] and imgheight == src.shape[0]

            joints_vis_17 = label['joint_vis_17'].copy()
            joints_cam_17 = label['joint_cam_17'].copy()

            joints_img_29 = label['joint_img_29'].copy()
            joints_vis_29 = label['joint_vis_29'].copy()
            joints_cam_29 = label['joint_cam_29'].copy()
            if 'joint_vis_xyz' in label:
                # For EFT-COCO only, where joints_vis_29(coco label) does not have depth visibility.
                joints_vis_xyz = label['joint_vis_xyz'].copy()
            else:
                joints_vis_xyz = None

            if 'joint_img_11' in label:
                joints_11_uvd = label['joint_img_11'].copy()
            else:
                joints_11_uvd = np.zeros((11, 3, 2), dtype=np.float32)
            if 'joint_cam_11' in label:
                joints_cam_11 = label['joint_cam_11']
                joints_vis_11 = np.ones((11, 3), dtype=np.float32)
            else:
                joints_cam_11 = np.zeros((11, 3), dtype=np.float32)
                joints_vis_11 = np.zeros((11, 3), dtype=np.float32)

            gt_joints_29 = np.zeros((29, 3, 2), dtype=np.float32)
            gt_joints_29[:, :, 0] = joints_img_29.copy()
            gt_joints_29[:, :, 1] = joints_vis_29.copy()

            beta = label['beta'].copy()
            theta = label['theta'].copy()

            input_size = self._input_size

            if self._train and self._add_dpg:
                bbox = add_DPG(bbox, imgwidth, imgheight)

            xmin, ymin, xmax, ymax = bbox
            center, scale = bbox_xywh_to_cs(
                xmin, ymin, xmax - xmin, ymax - ymin, self._aspect_ratio, scale_mult=self._scale_mult)
            xmin, ymin, xmax, ymax = bbox_cs_to_xyxy(center, scale)

            #----------------------------- Occlusion -----------------------------#
            if self._train and self._occlusion:
                add_occlusion(src, xmin, xmax, ymin, ymax, imgwidth, imgheight)

            #----------------------------- Half body transform -----------------------------#
            if self._train and (np.sum(joints_vis_29[:, 0]) > self.num_joints_half_body \
                           and np.random.rand() < self.prob_half_body):

                c_half_body, s_half_body = self.half_body_transform(joints_img_29, joints_vis_29)
                if c_half_body is not None and s_half_body is not None:
                    center, scale = c_half_body, s_half_body

            #----------------------------- Scale -----------------------------#
            if self._train and self._scale_factor > 0:
                sf = self._scale_factor
                scale = scale * np.clip(np.random.randn() * sf + 1, 1 - sf, 1 + sf)
            else:
                scale = scale * 1.0

            #----------------------------- Rotation -----------------------------#
            if self._train and self._rot > 0:
                rf = self._rot
                r = np.clip(np.random.randn() * rf, -rf * 2, rf * 2) if random.random() <= 0.6 else 0
            else:
                r = 0

            #----------------------------- Flip -----------------------------#
            joints_29_uvd = gt_joints_29
            joints_rel_17_xyz = joints_cam_17 - joints_cam_17[[self.root_idx]]
            joints_rel_24_xyz = joints_cam_29[:24] - joints_cam_29[[self.root_idx]]
            joints_rel_11_xyz = joints_cam_11 - joints_cam_29[[self.root_idx]]

            if self._train and self._flip and random.random() > 0.5:
                assert src.shape[2] == 3
                src = src[:, ::-1, :]

                joints_29_uvd = flip_joints_vis(joints_29_uvd, imgwidth, self._joint_pairs_29)
                joints_11_uvd = flip_joints_vis(joints_11_uvd, imgwidth, self._joint_pairs_11)
                joints_rel_17_xyz = flip_xyz_joints_3d(joints_rel_17_xyz, self._joint_pairs_17)
                joints_rel_24_xyz = flip_xyz_joints_3d(joints_rel_24_xyz, self._joint_pairs_24)
                joints_rel_11_xyz = flip_xyz_joints_3d(joints_rel_11_xyz, self._joint_pairs_11)
                theta = flip_thetas(theta, self._joint_pairs_24)
                center[0] = imgwidth - center[0] - 1

            #----------------------------- Transform image -----------------------------#
            inp_h, inp_w = input_size
            trans = get_affine_transform(center, scale, r, [inp_w, inp_h])
            img = cv2.warpAffine(src, trans, (int(inp_w), int(inp_h)), flags=cv2.INTER_LINEAR)
            bbox = bbox_cs_to_xyxy(center, scale)

            #----------------------------- Transform joints -----------------------------#
            # Transform 2D joints
            for i in range(joints_29_uvd.shape[0]):
                if joints_29_uvd[i, 0, 1] > 0.0:
                    joints_29_uvd[i, 0:2, 0] = affine_transform(joints_29_uvd[i, 0:2, 0], trans)
            for i in range(joints_11_uvd.shape[0]):
                if joints_11_uvd[i, 0, 1] > 0.0:
                    joints_11_uvd[i, 0:2, 0] = affine_transform(joints_11_uvd[i, 0:2, 0], trans)

            # Rotate global orientation
            theta[0, :3] = rotate_axis_angle(theta[0, :3], r)
            theta_rot_mat = batch_rodrigues_numpy(theta).reshape(24 * 9)
            theta_24_weights = np.ones((24 * 9))

            # Rotate 3D joints
            joints_rel_17_xyz = rotate_xyz_jts(joints_rel_17_xyz, r)
            joints_rel_24_xyz = rotate_xyz_jts(joints_rel_24_xyz, r)
            joints_rel_11_xyz = rotate_xyz_jts(joints_rel_11_xyz, r)

            #----------------------------- Target generation -----------------------------#
            target_uvd_29, target_weight_29 = self._uvd_target_generator(joints_29_uvd, 29, inp_h, inp_w)
            target_weight_29 *= joints_vis_29.reshape(-1)
            target_uvd_11, target_weight_11 = self._uvd_target_generator(joints_11_uvd, 11, inp_h, inp_w)
            target_xyz_17, target_weight_17 = self._xyz_target_generator(joints_rel_17_xyz, joints_vis_17, 17)
            target_weight_17 *= joints_vis_17.reshape(-1)
            if joints_vis_xyz is None:
                target_xyz_24, target_weight_24 = self._xyz_target_generator(joints_rel_24_xyz, joints_vis_29[:24, :], 24)
                target_weight_24 *= joints_vis_29[:24, :].reshape(-1)
            else:
                target_xyz_24, target_weight_24 = self._xyz_target_generator(joints_rel_24_xyz, joints_vis_xyz[:24, :], 24)
                target_weight_24 *= joints_vis_xyz[:24, :].reshape(-1)
            target_xyz_11, target_weight_11_xyz = self._xyz_target_generator(joints_rel_11_xyz, joints_vis_11, 11)
            target_weight_11_xyz *= joints_vis_11.reshape(-1)

            #----------------------------- Others -----------------------------#
            trans_inv = get_affine_transform(center, scale, r, [inp_w, inp_h], inv=True).astype(np.float32)

            intrinsic_param = get_intrinsic_metrix(label['f'], label['c']).astype(np.float32) if 'f' in label.keys() \
                else np.array([[self.focal_length, 0., imgwidth*0.5],
                               [0., self.focal_length, imgheight*0.5],
                               [0., 0., 1.]]).astype(np.float32)

            joint_root = 0.001 * label['root_cam'].astype(np.float32) if 'root_cam' in label.keys() \
                else np.array([0., 0., 3.]).astype(np.float32)

        assert img.shape[2] == 3
        #----------------------------- Color augmentation -----------------------------#
        if self._train:
            c_high = 1 + self._color_factor
            c_low = 1 - self._color_factor
            img[:, :, 0] = np.clip(img[:, :, 0] * random.uniform(c_low, c_high), 0, 255)
            img[:, :, 1] = np.clip(img[:, :, 1] * random.uniform(c_low, c_high), 0, 255)
            img[:, :, 2] = np.clip(img[:, :, 2] * random.uniform(c_low, c_high), 0, 255)

        #----------------------------- Convert image to tensor -----------------------------#
        img = im_to_torch(img)

        # mean
        img[0].add_(-0.485)
        img[1].add_(-0.456)
        img[2].add_(-0.406)

        # std
        img[0].div_(0.229)
        img[1].div_(0.224)
        img[2].div_(0.225)

        img_center = np.array([float(imgwidth) * 0.5, float(imgheight) * 0.5])

        if 'beta_kid' not in label:
            kid_betas = np.array([0], dtype=np.float32)
        else:
            kid_betas = label['beta_kid'].copy()

        if not self.with_smpl:
            output = {
                'type': '3d_skel',
                'image': img,
                'target_uvd': torch.from_numpy(target_uvd).float(),
                'target_weight': torch.from_numpy(target_weight).float(),
                'target_xyz': torch.from_numpy(target_xyz).float(),
                'target_xyz_weight': torch.from_numpy(target_xyz_weight).float(),
                'bbox': torch.Tensor(bbox).float(),
                'trans_inv': torch.from_numpy(trans_inv).float(),
                'intrinsic_param': torch.from_numpy(intrinsic_param).float(),
                'joint_root': torch.from_numpy(joint_root).float(),
                'img_center': torch.from_numpy(img_center).float(),
                'kid_betas' : torch.from_numpy(kid_betas).float(),
            }

        else:
            output = {
                'type': '3d_smpl',
                'image': img,
                'target_theta': torch.from_numpy(theta_rot_mat).float(),
                'target_theta_weight': torch.from_numpy(theta_24_weights).float(),
                'target_beta': torch.from_numpy(beta).float(),
                'target_smpl_weight': torch.ones(1).float(),
                'target_uvd_29': torch.from_numpy(target_uvd_29).float(),
                'target_weight_29': torch.from_numpy(target_weight_29).float(),
                'target_uvd_11': torch.from_numpy(target_uvd_11).float(),
                'target_weight_11': torch.from_numpy(target_weight_11).float(),
                'target_xyz_24': torch.from_numpy(target_xyz_24).float(),
                'target_weight_24': torch.from_numpy(target_weight_24).float(),
                'target_xyz_17': torch.from_numpy(target_xyz_17).float(),
                'target_weight_17': torch.from_numpy(target_weight_17).float(),
                'target_xyz_11': torch.from_numpy(target_xyz_11).float(),
                'target_weight_11_xyz': torch.from_numpy(target_weight_11_xyz).float(),
                'bbox': torch.Tensor(bbox).float(),
                'trans_inv': torch.from_numpy(trans_inv).float(),
                'intrinsic_param': torch.from_numpy(intrinsic_param).float(),
                'joint_root': torch.from_numpy(joint_root).float(),
                'img_center': torch.from_numpy(img_center).float(),
                'kid_betas' : torch.from_numpy(kid_betas).float(),
            }
        return output

    def half_body_transform(self, joints, joints_vis):
        upper_joints = []
        lower_joints = []
        for joint_id in range(joints.shape[0]):
            if joints_vis[joint_id][0] > 0:
                if joint_id in self.upper_body_ids:
                    upper_joints.append(joints[joint_id])
                else:
                    lower_joints.append(joints[joint_id])

        if np.random.randn() < 0.5 and len(upper_joints) > 2:
            selected_joints = upper_joints
        else:
            selected_joints = lower_joints if len(lower_joints) > 2 else upper_joints

        if len(selected_joints) < 2:
            return None, None

        selected_joints = np.array(selected_joints, dtype=np.float32)
        center = selected_joints.mean(axis=0)[:2]

        left_top = np.amin(selected_joints, axis=0)
        right_bottom = np.amax(selected_joints, axis=0)

        w = right_bottom[0] - left_top[0]
        h = right_bottom[1] - left_top[1]

        if w > self._aspect_ratio * h:
            h = w * 1.0 / self._aspect_ratio
        elif w < self._aspect_ratio * h:
            w = h * self._aspect_ratio

        scale = np.array([w * 1.0 / self.pixel_std,
                          h * 1.0 / self.pixel_std], dtype=np.float32)

        scale = scale * 1.5

        return center, scale


# -*- coding: utf-8 -*-

from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404

from django.core.mail import send_mail
from django.conf import settings

from subscriptions.forms import SubscriptionForm
from subscriptions.models import Subscription

def subscribe(request):
	if request.method == 'POST':
		return create(request)
	else:
		return new(request)

def new(request):
	form = SubscriptionForm()
	"""
	form = SubscriptionForm({
		'name': 'Entre o seu nome',
		'cpf': 'Digite seu CPF sem pontos',
		'email': 'Informe o seu email',
		'phone': 'Qual o seu telefone de contato?'
	})
	"""

	context = RequestContext(request, {'form': form})
	return render_to_response('subscriptions/new.html', context)

def create(request):
	form = SubscriptionForm(request.POST)
	if not form.is_valid():
		context = RequestContext(request, {'form': form})
		return render_to_response('subscriptions/new.html', context)

	subscription = form.save()

	send_mail(
		subject=u'Cadastrado com sucesso',
		message=u'Obrigado pela sua inscrição!',
		from_email=settings.DEFAULT_FROM_EMAIL,
		recipient_list=[subscription.email]
	)

	return HttpResponseRedirect(
		reverse('subscriptions:success', args=[subscription.pk])
	)

def success(request, id):
	subscription = get_object_or_404(Subscription, pk=id)
	context = RequestContext(request, {'subscription': subscription})
	return render_to_response('subscriptions/success.html', context)


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

import requests
from bs4 import BeautifulSoup
from functools import cmp_to_key
import datetime
import subprocess

import os

KERNEL_FETCH_URL = 'http://kernel.ubuntu.com/~kernel-ppa/mainline/'

def write_log(version_number=None, warning=None):
    with open('/root/kernel_update.log', 'a') as f:
        if version_number:
            f.write(str(datetime.datetime.now()) + ' updates kernel: ' + version_number + '\n')
        if warning:
            f.write('----------\n' + str(datetime.datetime.now()) + ' has a WARNING!!!\n----------\n' + warning + '\n----------\n')

# get kernel version
def get_kernel_version():
    # use `uname -r`
    return subprocess.getoutput('uname -r').split('-')[0]

# companion
def cmp(s1, s2):
    s1 = s1.split('.')
    s2 = s2.split('.')
    for i in range(max(len(s1), len(s2))):
        if i >= len(s1): return -1
        if i >= len(s2): return 1
        if int(s1[i]) != int(s2[i]):
            return int(s1[i]) - int(s2[i])

    return 0

def init():
    soup = BeautifulSoup(requests.get(KERNEL_FETCH_URL).text, "lxml")

    a_list_from_html = soup.find_all('a')[19: ]
    version_list = [ i.text[1:-1] for i in a_list_from_html if i.text.find('-') == -1 ]
    max_version = max(version_list, key = cmp_to_key(cmp))

    if cmp(max_version, get_kernel_version()) > 0:
        base_url = 'http://kernel.ubuntu.com/~kernel-ppa/mainline/v'+max_version+'/'
        new_soup = BeautifulSoup(requests.get(base_url).text, 'lxml')
        download_available_url = new_soup.find_all('a')
        download_headers_all_url = ''
        for url in download_available_url:
            if url.text.find('all') != -1:
                download_headers_all_url = base_url+url['href']
                break
        download_available_url = [ base_url+url['href'] for url in download_available_url if url.text.find('amd64') != -1 and url.text.find('generic') != -1 ][:2]
        download_available_url.insert(0, download_headers_all_url)

        os.system('rm linux-*')
        os.system('wget ' + ' '.join(download_available_url))
        os.system('dpkg -i linux-*')

        write_log(version_number=max_version)

if __name__ == '__main__':
    try:
        init()
    except Exception as e:
        write_log(warning=str(e))