import gradio as gr
import json
from pathlib import Path
import re
from bs4 import BeautifulSoup
import base64

fileid2json = json.loads(Path("fileid2json.json").read_text())
fileid2image = json.loads(Path("fileid2image.json").read_text())

autov22fileid = json.loads(Path("autov22fileid.json").read_text())
filename2fileid = json.loads(Path("filename2fileid.json").read_text())
name2fileid = json.loads(Path("name2fileid.json").read_text())


def fileids2html(fileids, query):
    html = BeautifulSoup("<div></div>", "html.parser")
    for fileid in sorted(list(fileids), reverse=True, key=lambda x:int(x)):
        src = "https://huggingface.co/front/assets/huggingface_logo-noborder.svg"
        if fileid in fileid2image:
            src = fileid2image[fileid.strip()]
        div = html.new_tag("div", style="height:16rem;")
        h1 = html.new_tag("h1")
        a = html.new_tag("a", target="_blank")
        a.append(str(fileid))
        h1.append(a)
        textarea = html.new_tag("textarea", dir="ltr", style='color:var(--body-text-color);display:inline-block;overflow:auto;width:calc(100% - 256px);height:100%;background:var(--block-background-fill);')
        html.append(h1)
        html.append(div)
        div.append(textarea)
        div.append(html.new_tag("img", src=src, style='display:inline-block;max-width:256px;height:100%;vertical-align:initial;'))
        if fileid in fileid2json:
            j = fileid2json[fileid.strip()]
            a["href"] = j["notes"]
            textarea.append(json.dumps(j, indent=2, ensure_ascii=False))
            j = base64.b64encode(json.dumps(j, indent=2, ensure_ascii=False).encode()).decode()
            a2 = html.new_tag("a", download="{}.json".format(query), href="data:application/json;base64,{}".format(j), style="margin-left:3rem;")
            a2.append("Save JSON")
            h1.append(a2)
            html.append(html.new_tag("hr", style="margin-top:1rem;margin-bottom:1rem;"))
    return str(html)




def greet(query):
    fileids = set()
    fileid = query
    hit = None

    if query.upper() in autov22fileid:
        fileid = str(autov22fileid[query.upper()])
        fileids.add(fileid)
        hit = True
    if re.sub(r'\..*$', "", query) in filename2fileid:
        fileid = str(filename2fileid[re.sub(r'\..*$', "", query)])
        fileids.add(fileid)
        hit = True
    if query in name2fileid:
        fileid = str(name2fileid[query])
        fileids.add(fileid)
    if hit is not True:
        for k, v in [(k.lower(), v) for k, v in name2fileid.items()]:
            if re.search(re.compile(query), k):
                fileid = str(v)
                fileids.add(fileid)
    
    return fileids2html(fileids, query)

iface = gr.Interface(fn=greet, inputs="text", outputs="html", allow_flagging='never', css='#component-4 { max-width: 16rem; }')
iface.launch(server_name="0.0.0.0")