import random
import fire
import json
import os
import numpy as np
import tensorflow as tf
import pytumblr
import mysql.connector
import datetime
from random import seed
import model, sample, encoder

def interact_model(
    model_name='1558M',
    seed=None,
    nsamples=1,
    batch_size=1,
    length=None,
    temperature=.7,
    top_k=10,
    top_p=1,
    models_dir='models',
):
    # Autenticazione
    client = pytumblr.TumblrRestClient(
      '',
      '',
      '',
      ''
    )
   # Al fine di mantenere la sicurezza del mio account le due coppie di chiavi per la connessione a Tumblr sono state eliminate da questo file.


   # Connessione al DB
    mydb = mysql.connector.connect(
      host="localhost",
      user="root",
      password="",
      database="cometa"
    )

    print(mydb)
    cursor = mydb.cursor()
    
    # Generazione query
    print("prima di eseguire la query")
    cursor.execute("SELECT testo FROM prompts ORDER BY RAND() LIMIT 1")
    print("dopo query")
    for (testo) in cursor:
      print("{}".format(testo))
    # Formattazione del prompt
    testoBuono = "{}".format(testo)
    testoBuono=testoBuono.replace("(","")
    testoBuono=testoBuono.replace(")","")
    testoBuono=testoBuono.replace("'","")
    testoBuono=testoBuono.replace(",","")
    print(testoBuono)


    client.info() # Riceve e trattiene le informazioni del profilo
    blogName='unlikelycrownkitty'
    models_dir = os.path.expanduser(os.path.expandvars(models_dir))
    if batch_size is None:
        batch_size = 1
    assert nsamples % batch_size == 0
    
    # Carico il modello dalla directory
    enc = encoder.get_encoder(model_name, models_dir)
    hparams = model.default_hparams()
    with open(os.path.join(models_dir, model_name, 'hparams.json')) as f:
        hparams.override_from_dict(json.load(f))

    # Eseguo un controllo per verificare che il prompt non sia eccessivamente lungo
    if length is None:
        length = hparams.n_ctx // 2
    elif length > hparams.n_ctx:
        raise ValueError("Can't get samples longer than window size: %s" % hparams.n_ctx)

    
    # Avvio il modello con i parametri
    with tf.Session(graph=tf.Graph()) as sess:
        context = tf.placeholder(tf.int32, [batch_size, None])
        np.random.seed(seed)
        tf.set_random_seed(seed)
        output = sample.sample_sequence(
            hparams=hparams, length=length,
            context=context,
            batch_size=batch_size,
            temperature=temperature, top_k=top_k, top_p=top_p
        )
        continua=True
        # Inizio la generazione del testo
        saver = tf.train.Saver()
        ckpt = tf.train.latest_checkpoint(os.path.join(models_dir, model_name))
        saver.restore(sess, ckpt)
        while continua:
            raw_text = testoBuono
            # raw_text = f.read()
            while not raw_text:
                print('The file is empty! Write something yourself.')
                raw_text = input("Model prompt >>> ")
            context_tokens = enc.encode(raw_text)
            generated = 0
            for _ in range(nsamples // batch_size):
                out = sess.run(output, feed_dict={
                    context: [context_tokens for _ in range(batch_size)]
                })[:, len(context_tokens):]
                for i in range(batch_size):
                    generated += 1
                    text = enc.decode(out[i])
                    print("=" * 40 + " SAMPLE " + str(generated) + " " + "=" * 40)
                    print(text)
            print("=" * 80)
            # Pubblico il testo generato
            client.create_text(blogName, state="published", slug="testing-text-posts",title=raw_text, body=text)
            print('Continue? y/n')
            risposta=input()
            if risposta.lower() in ['y', 'yes']:
                continua=True
            else:
                continua=False
                exit()



if __name__ == '__main__':
    fire.Fire(interact_model())


[(25, 'pytumblr.TumblrRestClient', 'pytumblr.TumblrRestClient', False, 'import pytumblr\n'), (68, 'encoder.get_encoder', 'encoder.get_encoder', False, 'import model, sample, encoder\n'), (69, 'model.default_hparams', 'model.default_hparams', False, 'import model, sample, encoder\n'), (62, 'os.path.expandvars', 'os.path.expandvars', False, 'import os\n'), (82, 'tensorflow.placeholder', 'tf.placeholder', True, 'import tensorflow as tf\n'), (83, 'numpy.random.seed', 'np.random.seed', True, 'import numpy as np\n'), (84, 'tensorflow.set_random_seed', 'tf.set_random_seed', True, 'import tensorflow as tf\n'), (85, 'sample.sample_sequence', 'sample.sample_sequence', False, 'import model, sample, encoder\n'), (93, 'tensorflow.train.Saver', 'tf.train.Saver', True, 'import tensorflow as tf\n'), (70, 'os.path.join', 'os.path.join', False, 'import os\n'), (71, 'json.load', 'json.load', False, 'import json\n'), (94, 'os.path.join', 'os.path.join', False, 'import os\n'), (81, 'tensorflow.Graph', 'tf.Graph', True, 'import tensorflow as tf\n')]