Spaces:
Runtime error
Runtime error
Ron Au commited on
Commit ·
61d63d5
1
Parent(s): 0731409
Initial Commit
Browse filesFiles changed (6)
- app.py+30-8
- dataset.pyAdded+19
- index.html
- index.js+89-11
- inference.py+5-4
- style.css+39-5
3 unmodified lines45678910111213142 unmodified lines17181920212223242526272829304 unmodified lines353637383940414243443 unmodified linesfrom http.server import SimpleHTTPRequestHandler, ThreadingHTTPServerfrom urllib.parse import parse_qs, urlparsefrom inference import t5_infer# https://huggingface.co/settings/tokens# https://huggingface.co/spaces/{username}/{space}/settingsAPI_TOKEN = os.getenv('BIG_GAN_TOKEN')class RequestHandler(SimpleHTTPRequestHandler):def do_GET(self):2 unmodified linesreturn SimpleHTTPRequestHandler.do_GET(self)if self.path.startswith("/biggan_infer"):input = parse_qs(urlparse(self.path).query).get("input", None)[0]output = requests.request("POST","https://api-inference.huggingface.co/models/osanseviero/BigGAN-deep-128",headers={"Authorization": f"Bearer {API_TOKEN}"},data=json.dumps(input))self.send_response(200)4 unmodified linesreturn SimpleHTTPRequestHandlerelif self.path.startswith("/t5_infer"):input = parse_qs(urlparse(self.path).query).get("input", None)output = t5_infer(input)self.send_response(200)self.send_header("Content-Type", "application/json")3 unmodified lines456789101112131415162 unmodified lines192021222324252627282930313233344 unmodified lines394041424344454647484950515253545556575859606162636465663 unmodified linesfrom http.server import SimpleHTTPRequestHandler, ThreadingHTTPServerfrom urllib.parse import parse_qs, urlparsefrom inference import infer_t5from dataset import query_emotion# https://huggingface.co/settings/tokens# https://huggingface.co/spaces/{username}/{space}/settingsAPI_TOKEN = os.getenv("BIG_GAN_TOKEN")class RequestHandler(SimpleHTTPRequestHandler):def do_GET(self):2 unmodified linesreturn SimpleHTTPRequestHandler.do_GET(self)if self.path.startswith("/infer_biggan"):url = urlparse(self.path)query = parse_qs(url.query)input = query.get("input", None)[0]output = requests.request("POST","https://api-inference.huggingface.co/models/osanseviero/BigGAN-deep-128",headers={"Authorization": f"Bearer {API_TOKEN}"},data=json.dumps(input),)self.send_response(200)4 unmodified linesreturn SimpleHTTPRequestHandlerelif self.path.startswith("/infer_t5"):url = urlparse(self.path)query = parse_qs(url.query)input = query.get("input", None)[0]output = infer_t5(input)self.send_response(200)self.send_header("Content-Type", "application/json")self.end_headers()self.wfile.write(json.dumps({"output": output}).encode("utf-8"))return SimpleHTTPRequestHandlerelif self.path.startswith("/query_emotion"):url = urlparse(self.path)query = parse_qs(url.query)start = int(query.get("start", None)[0])end = int(query.get("end", None)[0])output = query_emotion(start, end)self.send_response(200)self.send_header("Content-Type", "application/json")
12345678910111213141516171819from datasets import load_dataset
dataset = load_dataset("emotion", split="train")
emotions = dataset.info.features["label"].names
def query_emotion(start, end): rows = dataset[start:end] texts, labels = [rows[k] for k in rows.keys()]
observations = []
for i, text in enumerate(texts): observations.append({ "text": text, "emotion": emotions[labels[i]], })
return observations12345678910111213141516171819202122232425263 unmodified lines30313233343536373839402 unmodified lines434445464748if (document.location.search.includes("dark-theme=true")) {document.body.classList.add("dark-theme");}const textToImage = async (text) => {const inferenceResponse = await fetch(`biggan_infer?input=${text}`);const inferenceBlob = await inferenceResponse.blob();return URL.createObjectURL(inferenceBlob);};const translateText = async (text) => {const inferResponse = await fetch(`t5_infer?input=${text}`);const inferJson = await inferResponse.json();return inferJson.output;};const imageGenSelect = document.getElementById("image-gen-input");const imageGenImage = document.querySelector(".image-gen-output");const textGenForm = document.querySelector(".text-gen-form");imageGenSelect.addEventListener("change", async (event) => {const value = event.target.value;try {3 unmodified lines}});textGenForm.addEventListener("submit", async (event) => {event.preventDefault();const textGenInput = document.getElementById("text-gen-input");const textGenParagraph = document.querySelector(".text-gen-output");try {textGenParagraph.textContent = await translateText(textGenInput.value);2 unmodified lines}});textToImage(imageGenSelect.value).then((image) => (imageGenImage.src = image)).catch(console.error);12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273743 unmodified lines78798081828384858687882 unmodified lines919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126if (document.location.search.includes('dark-theme=true')) {document.body.classList.add('dark-theme');}const textToImage = async (text) => {const inferenceResponse = await fetch(`/infer_biggan?input=${text}`);const inferenceBlob = await inferenceResponse.blob();return URL.createObjectURL(inferenceBlob);};const translateText = async (text) => {const inferResponse = await fetch(`/infer_t5?input=${text}`);const inferJson = await inferResponse.json();return inferJson.output;};const queryDataset = async (start, end) => {const queryResponse = await fetch(`/query_emotion?start=${start}&end=${end}`);const queryJson = await queryResponse.json();return queryJson.output;};const updateTable = async (cursor, range = 5) => {const table = document.querySelector('.dataset-output');const fragment = new DocumentFragment();const observations = await queryDataset(cursor, cursor + range);for (const observation of observations) {let row = document.createElement('tr');let text = document.createElement('td');let emotion = document.createElement('td');text.textContent = observation.text;emotion.textContent = observation.emotion;row.appendChild(text);row.appendChild(emotion);fragment.appendChild(row);}table.innerHTML = '';table.appendChild(fragment);table.insertAdjacentHTML('afterbegin',`<thead><tr><td>text</td><td>emotion</td></tr></thead>`);};const imageGenSelect = document.getElementById('image-gen-input');const imageGenImage = document.querySelector('.image-gen-output');const textGenForm = document.querySelector('.text-gen-form');const tableButtonPrev = document.querySelector('.table-previous');const tableButtonNext = document.querySelector('.table-next');let cursor = 0;const RANGE = 5;const LIMIT = 16_000;imageGenSelect.addEventListener('change', async (event) => {const value = event.target.value;try {3 unmodified lines}});textGenForm.addEventListener('submit', async (event) => {event.preventDefault();const textGenInput = document.getElementById('text-gen-input');const textGenParagraph = document.querySelector('.text-gen-output');try {textGenParagraph.textContent = await translateText(textGenInput.value);2 unmodified lines}});tableButtonPrev.addEventListener('click', () => {cursor = cursor > RANGE ? cursor - RANGE : 0;if (cursor < RANGE) {tableButtonPrev.classList.add('hidden');}if (cursor < LIMIT - RANGE) {tableButtonNext.classList.remove('hidden');}updateTable(cursor);});tableButtonNext.addEventListener('click', () => {cursor = cursor < LIMIT - RANGE ? cursor + RANGE : cursor;if (cursor >= RANGE) {tableButtonPrev.classList.remove('hidden');}if (cursor >= LIMIT - RANGE) {tableButtonNext.classList.add('hidden');}updateTable(cursor);});textToImage(imageGenSelect.value).then((image) => (imageGenImage.src = image)).catch(console.error);updateTable(cursor).then((image) => (imageGenImage.src = image)).catch(console.error);
2 unmodified lines3456789102 unmodified linestokenizer = T5Tokenizer.from_pretrained("t5-small")model = T5ForConditionalGeneration.from_pretrained("t5-small")def t5_infer(input):input_ids = tokenizer(input, return_tensors="pt").input_idsoutputs = model.generate(input_ids)return tokenizer.decode(outputs[0], skip_special_tokens=True)2 unmodified lines345678910112 unmodified linestokenizer = T5Tokenizer.from_pretrained("t5-small")model = T5ForConditionalGeneration.from_pretrained("t5-small")def infer_t5(input):input_ids = tokenizer(input, return_tensors="pt").input_idsoutputs = model.generate(input_ids)return tokenizer.decode(outputs[0], skip_special_tokens=True)
11 unmodified lines121314151617181920212217 unmodified lines40414243444546474811 unmodified lines}main {display: flex;flex-direction: column;align-items: center;max-width: 80rem;text-align: center;}a {17 unmodified lineswidth: 70%;}.text-gen-output {min-height: 1rem;margin: 0;align-self: start;border: 2px solid var(--text);}11 unmodified lines121314151617181920212223242517 unmodified lines4344454647484950515253545556575859606162636465666768697071727374757677787980818211 unmodified lines}main {max-width: 80rem;text-align: center;}section {display: flex;flex-direction: column;align-items: center;}a {17 unmodified lineswidth: 70%;}button {cursor: pointer;}.text-gen-output {min-height: 1.2rem;margin: 1rem;align-self: start;border: 0.5px solid grey;}#dataset button {width: 6rem;margin: 0.5rem;}#dataset button.hidden {visibility: hidden;}table {max-width: 40rem;text-align: left;border-collapse: collapse;}thead {font-weight: bold;}td {padding: 0.5rem;}td:not(thead td) {border: 0.5px solid grey;}
app.py+30-8
dataset.pyAdded+19
index.html
index.js+89-11
inference.py+5-4
style.css+39-5