from transformers import BlenderbotTokenizer, BlenderbotForConditionalGeneration
import torch
import gradio as gr
# PersistDataset -----
import os
import csv
import gradio as gr
from gradio import inputs, outputs
import huggingface_hub
from huggingface_hub import Repository, hf_hub_download, upload_file
from datetime import datetime
DATASET_REPO_URL = "https://huggingface.co/datasets/awacke1/Carddata.csv"
DATASET_REPO_ID = "awacke1/Carddata.csv"
DATA_FILENAME = "Carddata.csv"
DATA_FILE = os.path.join("data", DATA_FILENAME)
HF_TOKEN = os.environ.get("HF_TOKEN")
SCRIPT = """
"""
try:
    hf_hub_download(
        repo_id=DATASET_REPO_ID,
        filename=DATA_FILENAME,
        cache_dir=DATA_DIRNAME,
        force_filename=DATA_FILENAME
    )
except:
    print("file not found")
repo = Repository(
    local_dir="data", clone_from=DATASET_REPO_URL, use_auth_token=HF_TOKEN
)
def generate_html() -> str:
    with open(DATA_FILE) as csvfile:
        reader = csv.DictReader(csvfile)
        rows = []
        for row in reader:
            rows.append(row)
        rows.reverse()
        if len(rows) == 0:
            return "no messages yet"
        else:
            html = "
"
            for row in rows:
                html += "
"
                html += f"{row['inputs']}"
                html += f"{row['outputs']}"
                html += "
"
            html += "
'.join(note_history[0].split(' ')[2:])]
        history = history[1:]
    return inputs, note_history, history
def add_note_to_history(note, note_history):
    """Add a note to the historical information"""
    note_history.append(note)
    note_history = ' '.join(note_history)
    return [note_history]
title = "Chatbot State of the Art now with Memory Saved to Dataset"
description = """Chatbot With Memory"""
def chat(message, history):
    history = history or []
    if history: 
        history_useful = [' '.join([str(a[0])+' '+str(a[1]) for a in history])]
    else:
        history_useful = []
    history_useful = add_note_to_history(message, history_useful)
    inputs = tokenizer(history_useful, return_tensors="pt")
    inputs, history_useful, history = take_last_tokens(inputs, history_useful, history)
    reply_ids = model.generate(**inputs)
    response = tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0]
    history_useful = add_note_to_history(response, history_useful)
    list_history = history_useful[0].split(' ')
    history.append((list_history[-2], list_history[-1]))
    store_message(message, response) # Save to dataset
    return history, history
gr.Interface(
    fn=chat,
    theme="huggingface",
    css=".footer {display:none !important}",
    inputs=["text", "state"],
    outputs=["chatbot", "state"],
    title=title,
    allow_flagging="never",
    description=f"Gradio chatbot backed by memory in a dataset repository.",
    article=f"The dataset repo is [{DATASET_REPO_URL}]({DATASET_REPO_URL})"
    ).launch()