Skip to content

Commit

Permalink
Added implementation made by @NaMJaG for key phrase suggestions under…
Browse files Browse the repository at this point in the history
… the prompt.
  • Loading branch information
ZeroCool940711 committed Oct 19, 2022
1 parent 5236d85 commit 345ea86
Show file tree
Hide file tree
Showing 11 changed files with 557 additions and 3 deletions.
85 changes: 85 additions & 0 deletions data/tags/key_phrases.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
{
"Photo": [
"Kodak Portra 400",
"Kodak Ektar 100",
"Kodak Portra 160 Professional",
"Ilford HP5 Plus",
"Kodak TRI-X 400",
"Ilford XP2S",
"Lomography Lady Grey",
"Fujifilm Velvia 50",
"Kodak Ektachrome E100",
"Fujifilm Velvia 100",
"Ilford Delta 3200",
"Fujicolor Superia 1600",
"Kodak T-Max P3200",
"Fujifilm Instax Film",
"Polaroid i\u2011Type Instant Film",
"Polaroid 600 Instant Film",
"Polaroid SX-70 Instant Film",
"focused",
"out of focus",
"sharp focus"
],
"Lighting": [
"blue hour",
"golden hour",
"dramatic backlighting",
"midday",
"volumetric lighting",
"subsurface scattering",
"cool twilight lighting",
"warm lighting",
"sunrise",
"beams of sunlight",
"god rays",
"light shafts",
"harsh sunlight",
"radiant glow",
"backlighting"
],
"Genre": [
"cyberpunk",
"steampunk",
"dieselpunk",
"fantasy",
"dark fantasy",
"scify"
],
"Style": [
"in the style of",
"silhouetted",
"noir",
"infographic",
"hyperrealistic"
],
"Abstract Concept": [
"hope",
"progressive",
"sainted",
"adequate",
"sufficient",
"reality",
"faithfulness",
"sensation",
"intend",
"likability",
"agnosticism",
"controllability",
"determinate",
"dignify",
"standpoint",
"imperative",
"absurd"
],
"Painting": [
"expressionist painting",
"detailed oil painting"
],
"Details": [
"intricate details",
"higly detailed",
"blurred",
"smooth"
]
}
10 changes: 10 additions & 0 deletions scripts/custom_components/dragable_number_input/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import os
import streamlit.components.v1 as components

def load():
parent_dir = os.path.dirname(os.path.abspath(__file__))
file = os.path.join(parent_dir, "main.js")

with open(file) as f:
javascript_main = f.read()
components.html(f"<script>{javascript_main}</script>")
110 changes: 110 additions & 0 deletions scripts/custom_components/dragable_number_input/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// iframe parent
var parentDoc = window.parent.document

// check for mouse pointer locking support, not a requirement but improves the overall experience
var havePointerLock = 'pointerLockElement' in parentDoc ||
'mozPointerLockElement' in parentDoc ||
'webkitPointerLockElement' in parentDoc;

// the pointer locking exit function
parentDoc.exitPointerLock = parentDoc.exitPointerLock || parentDoc.mozExitPointerLock || parentDoc.webkitExitPointerLock;

// how far should the mouse travel for a step 50 pixel
var pixelPerStep = 50;

// how many steps did the mouse move in as float
var movementDelta = 0.0;
// value when drag started
var lockedValue = 0;
// minimum value from field
var lockedMin = 0;
// maximum value from field
var lockedMax = 0;
// how big should the field steps be
var lockedStep = 0;
// the currently locked in field
var lockedField = null;

parentDoc.addEventListener('mousedown', (e) => {
// if middle is down
if(e.button === 1)
{
if(e.target.tagName === 'INPUT' && e.target.type === 'number')
{
e.preventDefault();
var field = e.target;
if(havePointerLock)
field.requestPointerLock = field.requestPointerLock || field.mozRequestPointerLock || field.webkitRequestPointerLock;

// save current field
lockedField = e.target;
// add class for styling
lockedField.classList.add("value-dragging");
// reset movement delta
movementDelta = 0.0;
// set to 0 if field is empty
if(lockedField.value === '')
lockedField.value = 0;

// save current field value
lockedValue = parseInt(lockedField.value);

if(lockedField.min === '' || lockedField.min === '-Infinity')
lockedMin = -99999999;
else
lockedMin = parseInt(lockedField.min);

if(lockedField.max === '' || lockedField.max === 'Infinity')
lockedMax = 99999999;
else
lockedMax = parseInt(lockedField.max);

if(lockedField.step === '' || lockedField.step === 'Infinity')
lockedStep = 1;
else
lockedStep = parseInt(lockedField.step);

// lock pointer if available
if(havePointerLock)
lockedField.requestPointerLock();

// add drag event
parentDoc.addEventListener("mousemove", onDrag, false);
}
}
});

onDrag = (e) => {
if(lockedField !== null)
{
// add movement to delta
movementDelta += e.movementX / pixelPerStep;
if(lockedField === NaN)
return;
// set new value
let value = lockedValue + Math.floor(Math.abs(movementDelta)) * lockedStep * Math.sign(movementDelta);
lockedField.focus();
lockedField.select();
parentDoc.execCommand('insertText', false /*no UI*/, Math.min(Math.max(value, lockedMin), lockedMax));
}
};

parentDoc.addEventListener('mouseup', (e) => {
// if mouse is up
if(e.button === 1)
{
// release pointer lock if available
if(havePointerLock)
parentDoc.exitPointerLock();

if(lockedField !== null && lockedField !== NaN)
{
// stop drag event
parentDoc.removeEventListener("mousemove", onDrag, false);
// remove class for styling
lockedField.classList.remove("value-dragging");
// remove reference
lockedField = null;
}
}
});
79 changes: 79 additions & 0 deletions scripts/custom_components/key_phrase_suggestions/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import os, requests, io, csv, json
from collections import defaultdict
import streamlit.components.v1 as components

# the google sheet document id (its in the url)
doc_id = "1WoMEpGiZia0AfngkT6sRUhGOwczBMyoslk2jhYNUoiw"
# the page to get from the document (also visible in the url, the gid)
key_phrase_sheet_id = "723922433"
# where to save the downloaded key_phrases
key_phrases_file = "data/tags/key_phrases.json"
# the loaded key phrase json as text
key_phrases_json = ""

def download_and_save_as_json(url):
global key_phrases_json

# download
r = requests.get(url)

# we need the bytes to decode utf-8 and use it in a stringIO
csv_bytes = r.content
# stringIO for parsing via csv.DictReader
str_file = io.StringIO(csv_bytes.decode('utf-8'), newline='\n')

reader = csv.DictReader(str_file, delimiter=',', quotechar='"')

# structure data in usable format (columns as arrays)
columnwise_table = defaultdict(list)
for row in reader:
for col, dat in row.items():
stripped = dat.strip()
if stripped != "":
columnwise_table[col].append(dat.strip())

# dump the data as json
key_phrases_json = json.dumps(columnwise_table, indent=4)

# save json so we don't need to download it every time
with open(key_phrases_file, 'w', encoding='utf-8') as jsonf:
jsonf.write(key_phrases_json)

def update_key_phrases():
url = f"https://docs.google.com/spreadsheets/d/{doc_id}/export?format=csv&gid={key_phrase_sheet_id}"
download_and_save_as_json(url)

def init():
global key_phrases_json
if not os.path.isfile(key_phrases_file):
update_key_phrases()
else:
with open(key_phrases_file) as f:
key_phrases_json = f.read()

def suggestion_area(placeholder):
# get component path
parent_dir = os.path.dirname(os.path.abspath(__file__))
# get file paths
javascript_file = os.path.join(parent_dir, "main.js")
stylesheet_file = os.path.join(parent_dir, "main.css")
parent_stylesheet_file = os.path.join(parent_dir, "parent.css")

# load file texts
with open(javascript_file) as f:
javascript_main = f.read()
with open(stylesheet_file) as f:
stylesheet_main = f.read()
with open(parent_stylesheet_file) as f:
parent_stylesheet = f.read()

# add suggestion area div box
html = "<div id='suggestion_area'>javascript failed</div>"
# add loaded style
html += f"<style>{stylesheet_main}</style>"
# set default variables
html += f"<script>var keyPhrases = {key_phrases_json};\nvar parentCSS = `{parent_stylesheet}`;\nvar placeholder='{placeholder}';</script>"
# add main java script
html += f"\n<script>{javascript_main}</script>"
# add component to site
components.html(html, width=None, height=None, scrolling=True)
40 changes: 40 additions & 0 deletions scripts/custom_components/key_phrase_suggestions/main.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
*
{
padding: 0px;
margin: 0px;
user-select: none;
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
}

body
{
width: 100%;
height: 100%;
}

#suggestionArea
{
overflow-y: auto;
width: 100%;
height: 100%;
}

span
{
border: 1px solid black;
border-radius: 5px;
background-color: rgb(38, 39, 48);
color: white;
display: inline-block;
padding: 5px;
margin-right: 3px;
cursor: pointer;
user-select: none;
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
}
Loading

0 comments on commit 345ea86

Please sign in to comment.