dreamdev / app.py
bigghuggs's picture
Update app.py
7757e4a verified
import gradio as gr
import json
import time
import numpy as np
import random
import os
import asyncio
import aiohttp
import requests
from PIL import Image
import io
#from textgen import getTextGen,multiprocessPrompts
def getTextGen(prompt, model=''):
from huggingface_hub import InferenceClient
client = InferenceClient(token=os.getenv('inference'))
import time
good = False
response = ''
tries = 0
model = model if model else "mistralai/Mixtral-8x7B-Instruct-v0.1"
while not good and tries<=3:
try:
print('getTextGen -- trying prompt: ', model, prompt[:50])
response = client.text_generation(prompt, model=model, max_new_tokens=2500, temperature=.7)
print('getTextGen -- generated: ', response[:50], '\n\n')
good = True
except:
time.sleep(.7)
model = ["mistralai/Mistral-7B-Instruct-v0.2", "microsoft/Phi-3-mini-4k-instruct", "google/gemma-7b"][tries]
tries += 1
print('getTextGen -- retrying prompt: ', model, prompt[:50])
return response
def multiprocessPrompts(prompts):
from multiprocessing import Pool
import time
start = time.time()
with Pool(5) as p:
responses = p.map(getTextGen, prompts)
print(time.time()-start)
return responses
js_func = """
function newScroll() {
var gallerys = document.getElementsByClassName("scroll");
for (var i = 0; i < box.length; i++) {
gallerys[i].style.overflow = "scroll";
}
}
"""
js_func = """
function refresh() {
const url = new URL(window.location);
if (url.searchParams.get('__theme') !== 'dark') {
url.searchParams.set('__theme', 'dark');
window.location.href = url.href;
}
}
"""
css = """
.scroll[style] {
overflow: scroll !important;
}
"""
bed_layout_new = ['Artwork', 'Curtains', 'Palette', 'Bedroom Rug', 'Mirrors', 'Bedroom Chair', 'Ottoman', 'Bedroom', 'Bedroom Set', 'Bedding']
living_layout_new = ['Artwork', 'Curtains', 'Palette', 'Rug', 'Armchairs', 'End Tables', 'Love Seats', 'Living Room', 'Sofas', 'End Tables', 'Plant Pots', 'Indoor Plants', 'Coffee tables', 'TV stands', 'Artwork']
img_url = 'https://dreamdemo.pythonanywhere.com/image/'
bedrooms = {'bedroom 1': img_url+'master bedroom.jpg', 'bedroom 2': img_url+'guest bedroom 2 beds.jpg', "bedroom 3": img_url+'boy bedroom 1 bed (n).jpg', "bedroom 4": img_url+'kids bedroom with bunkbeds a.jpg', 'living room': img_url+'living room.jpg'}
room_item_placeholder_images_dict = {'BEDROOM FURNITURE':{'Bedroom': img_url + 'gray bedroom.png', 'Bedroom Set':img_url + 'gray bedroom set.jpg', 'Beds':img_url + 'gray bed.jpg', 'Mattresses':img_url + 'gray matresses.jpg', 'Dressers': img_url + 'gray dresser.jpg', 'Nightstands': img_url + 'gray nightstand.jpg', 'Armoires':img_url + 'gray armoires.jpg', 'Chests of drawers': img_url + 'gray chest of drawers.jpg', 'Mirrors':img_url + 'gray bedroom mirror.jpg', 'Bedroom Chair':img_url + 'gray bedroom chair.jpg', 'Rug':img_url + 'gray bedroom rug.jpg', 'Bedding':img_url + 'gray bedding.jpg', 'paint':img_url + 'gray can of paint.jpg', 'Curtains':img_url + 'gray bedroom curtains.jpg', 'Artwork':img_url + 'gray bedroom art.jpg', 'Plant Pots':img_url + 'gray plant pots.jpg', 'Indoor Plants':img_url + 'gray plants.png'}, 'LIVING ROOM FURNITURE':{'Living Room': img_url + 'gray living room.png', 'Love Seats': img_url + 'gray love seat.jpg', 'Sofas': img_url + 'gray sofa.jpg', 'Armchairs':img_url + 'gray armchair.jpg', 'Coffee tables': img_url + 'gray coffee table.jpg', 'End Tables': img_url + 'gray end table.jpg', 'TV stands': img_url + 'gray tv stand.jpg', 'Bookshelves': img_url + 'gray bookshelf.jpg', 'Media consoles':img_url + 'gray media console.jpg', 'Sectionals':img_url + 'gray sectional.jpg', 'Recliners':img_url + 'gray recliner.jpg', 'Rug':img_url + 'gray living room rug.jpg', 'paint':img_url + 'gray can of paint.jpg', 'Curtains':img_url + 'gray living room curtains.jpg', 'Artwork':img_url + 'gray living room art.jpg', 'Plant Pots':img_url + 'gray plant pots.jpg', 'Indoor Plants':img_url + 'gray plants.png'}}
async def get(url, session):
try:
async with session.get(url=url, timeout=1.5) as response:
resp = await response.read()
print("Successfully got url {} with resp of length {}.".format(url, len(resp)))
return resp
except Exception as e:
print("Unable to get url {} due to {}.".format(url, e.__class__))
return None
async def main(urls):
async with aiohttp.ClientSession() as session:
ret = await asyncio.gather(*(get(url, session) for url in urls))
print("Finalized all. Return is a list of len {} outputs.".format(len(ret)))
return ret
async def post(url, session, json_data, headers, timeout=120):
try:
print('main_post: ', type(url), len(url), type(headers), len(headers), type(json_data), len(json_data))
async with session.request(method='post', url=url, timeout=timeout, headers=headers, json=json_data) as response:
resp = await response.read()
print("Successfully got url {} with resp of length {}.".format(url, len(resp)))
return resp
except Exception as e:
print("Unable to get url {} due to {}.".format(url, e.__class__))
return None
async def main_post(urls, headers, json_data, timeout=120):
async with aiohttp.ClientSession() as session:
ret = await asyncio.gather(*(post(url, session, json_data[i], headers[i], timeout=timeout) for i,url in enumerate(urls)))
print("Finalized all. Return is a list of len {} outputs.".format(len(ret)))
return ret
def getVizText(html):
from bs4 import BeautifulSoup, NavigableString, Tag
soup = BeautifulSoup(str(html), 'html.parser')
viz_text = [tag.text for tag in soup.find_all() if tag.text and len(tag.find_all())==0 and tag.name not in ['style', 'script', 'head', 'title', 'meta', '[document]'] and not isinstance(tag, NavigableString)]
viz_text_str = '...'.join(viz_text).replace('\\n', '').replace('\\t', '').replace('\n', '').replace('\t', '')
return viz_text_str
def findShoppingRelevantTerms(html):
viz_text_str = getVizText(str(html.decode("utf-8")))
search_terms = [' off ', ' availability ', ' available ', ' delivery ', ' deliver ', ' ship ', ' shipping ', ' return ', ' returns ', ' exchange ', ' exchanges ', ' material ', ' materials ']
found_terms = {t:(lambda text, term_loc: text[term_loc-300:term_loc+300])(viz_text_str, viz_text_str.lower().find(t.lower())) for t in search_terms if (t != ' off ' and t in viz_text_str) or (t == ' off ' and t in viz_text_str and ('%' in viz_text_str or '$' in viz_text_str))}
return found_terms
int_des_styles_keys = ['Mid-Century Modern', 'Coastal', 'Industrial', 'Scandinavian', 'Bohemian', 'Farmhouse', 'Contemporary', 'Transitional', 'Maximalist', 'Southwestern', 'Rustic', 'Mexican', 'Traditional', 'Art Deco', 'Shabby Chic']
styles_images = {style: {'bedroom': img_url + style + ' bedroom.jpg', 'living room': img_url + style + ' living room.jpg'} for style in int_des_styles_keys}
design_images = [(v['bedroom'], k) for k,v in styles_images.items()]
def writeForStoreProcessing(store, zipcode):
with open('C:\\Users\\Wayne\\Documents\\store_processors\\'+store+zipcode+'.json', 'w') as file:
json.dump({'store': store, 'zipcode': zipcode}, file)
alarm1 = ['If the matter of..', 'Should the issue of..', 'In the event that..', 'If..', 'Provided..', 'Given that..', 'Supposing..', 'Assuming..', 'On the condition that..', 'In the case that..', 'Provided that..', 'Given the scenario where..', 'Supposing the situation where..', 'Assuming the circumstance in which..', 'On the off-chance that..', 'In the event..', 'If the prospect of..', 'Provided the idea of..', 'Given the notion of..', 'Supposing the thought of..', 'Assuming the consideration of..', 'On the chance that..', 'In the instance..', 'If the possibility of..', 'Provided the eventuality of..', 'Given the contingency of..', 'Supposing the scenario of..', 'Assuming the situation of..', 'On the occasion that..', 'In the likelihood that..', 'If the prospect of..', 'Provided the idea of..', 'Given the notion of..', 'Supposing the thought of..', 'Assuming the consideration of..', 'On the chance that..', 'In the instance..', 'If the possibility of..', 'Provided the eventuality of..', 'Given the contingency of..', 'Supposing the scenario of..', 'Assuming the situation of..', 'On the occasion that..', 'In the likelihood that..', 'If the aspect of..', 'Provided the feature of..', 'Given the element of..', 'Supposing the component of..', 'Assuming the detail of..', 'On the chance that..', 'In the instance..', 'If the detail of..', 'Provided the facet of..', 'Given the dimension of..', 'Supposing the aspect of..', 'Assuming the attribute of..', 'On the occasion that..', 'In the likelihood that..', 'If the factor of..', 'Provided the variable of..', 'Given the element of..', 'Supposing the component of..', 'Assuming the detail of..', 'On the chance that..', 'In the instance..', 'If the particulars of..', 'Provided the specifics of..', 'Given the intricacies of..', 'Supposing the nuances of..', 'Assuming the subtleties of..', 'On the occasion that..', 'In the likelihood that..', 'If the matter of..', 'Provided the issue of..', 'Given the concern over..']
alarm2 = ['be a source of worry', 'is a cause for concern', 'is a source of unease', 'is a cause for apprehension', 'is a point of uneasiness', 'is a source of discomfort', 'is a cause for distress', 'is a cause for alarm', 'is a point of concern', 'troubles you', 'unsettles you', 'worries you', 'unnerves you', 'disturbs you', 'vexes you', 'distresses you', 'bothers you', 'unsettles you', 'worries you', 'unnerves you', 'disturbs you', 'vexes you', 'distresses you', 'is a source of unease for you', 'is a cause for apprehension', 'is a point of uneasiness', 'is a source of discomfort', 'is a cause for distress', 'is a point of concern', 'is a cause for alarm', 'is a point of concern', 'is a source of unease for you', 'is a cause for apprehension', 'is a point of uneasiness', 'is a source of discomfort', 'is a cause for distress', 'is a point of concern', 'is a cause for alarm', 'is a point of concern', 'is a source of unease for you', 'is a cause for apprehension', 'is a point of uneasiness', 'is a source of discomfort', 'is a cause for distress', 'is a point of concern', 'is a cause for alarm', 'is a point of concern', 'is a source of unease for you']
alarm3 = ['this might be worrying', 'this could be worrying to you', 'you might be worried', 'you may be worried', 'you may be concerned', 'you might be concerned', 'you might be uneasy', 'you may be uneasy', 'this may cause some apprehension', 'this could make you apprehensive', 'you may be apprehensive', 'you might be apprehensive', 'you may have some uneasiness', 'you might have some uneasiness', 'this might cause some uneasiness', 'it might make you uneasy', 'maybe you have some uneasiness', 'you may have some discomfort', 'you might have some discomfort', 'you could have some discomfort', 'maybe you have some discomfort', 'you may have some distress', 'this may cause some distress', 'it might give you some distress', 'you might have some distress', 'you could have some distress', 'maybe you have some distress', 'you might be alarmed', 'you may be alarmed', 'you could be alarmed', 'this might be alarming', 'you may find this alarming', 'maybe you are alarmed', 'you might find it concerning', 'you may find it concerning', 'you could find it concerning', 'maybe you find it concerning', 'this could be concerning', 'this may be concerning to you', 'you might be troubled', 'you may be troubled', 'you could be troubled', 'maybe you are troubled', 'you may be unsettled by this', 'you might be unsettled by this', 'you could be unsettled by this', 'maybe you are unsettled by this', 'you may find this unsettling', 'you might find it unsettling', 'you may find it worrying', 'you might find it worrying', 'you could find it worrying', 'maybe you find it worrying', 'you may find it unnerving', 'you might find it unnerving', 'you could find it unnerving', 'maybe you find it unnerving', 'maybe you are disturbed', 'maybe you find it disturbing', 'you may be disturbed', 'you might disturbed', 'this might disturb you', 'this may be disturbing to you', 'you could be disturbed this', 'you might be vexed', 'you may be vexed', 'you might find this vexing', 'maybe this is vexing', 'this maybe distresses you', 'this might distress you', 'this could distress you', 'you may be distressed', 'this might bother you', 'this could bother you', 'this maybe bothers you', 'you might be bothered', 'you may be bothered by this', 'this might be unsettling', 'this may be unsettling to you']
class Session():
def __init__(self):
self.match_counties = []
self.county = ""
self.prompts = {}
self.listing_details = {}
self.img_data = {}
self.bound_box_ij = (0,0)
self.stride_tm1 = 1
self.nudge = 1
self.impresh_image_rewrite = {}
self.Palettes = {}
self.activated_items = {}
self.filtered_files = {}
self.filtered_files_room = {}
self.filtered_files_style = {}
self.filtered_items_room = {}
self.filtered_items_style = {}
self.filtered_items_colors = {}
self.items = bed_layout_new
self.price = 'Affordable'.lower().split()[0]
self.bedsize = 'Queen'.lower().split()[0]
self.room_style = 'Mid-Century Modern'.lower().split()[0]
self.room_type = 'bedroom'
self.item_data = {}
self.item_data_ = {}
self.item_data_keys = {}
self.Palette_img = np.zeros((200,200,3)).astype(np.uint8)
self.Palette_img[:] = 128
self.default_img = np.zeros((200,200,3)).astype(np.uint8)
self.default_img[:] = 64
self.display_items = {}
self.Paletteid = None
self.clicked_displayed_product = ''
self.current_img_signature = self.img_id = None
self.updated_display = [((self.Palette_img if item == 'Palette' else self.default_img) if item in ['Palette', 'Living Room', 'Bedroom'] else room_item_placeholder_images_dict['LIVING ROOM FURNITURE'][item], item) for item in living_layout_new]
self.summary = {}
self.summary_closed = True
self.summary_radio = 'Complete'
self.product_means = {}
self.Palette_imgs = {}
self.Palette_ids = {}
self.Palettes_displayed = {}
self.items_layouts = {}
self.zipcode = '30054'
self.state = 'GA'
self.seshid = str(time.time())
self.time = ''
self.reset = False
self.locator_genid = {}
self.frmt_idxs_maps = {}
self.frmt_id_maps = {}
class AllSessions():
def __init__(self):
self.sessions = {}
all_sesh = AllSessions()
def getSesh(seshid):
print('getSesh: ', seshid, all_sesh.sessions.keys())
if seshid and seshid not in all_sesh.sessions:
all_sesh.sessions[seshid] = Session()
all_sesh.sessions[seshid].seshid = seshid
print('getSesh--instantiated sesh: ', seshid, all_sesh.sessions[seshid].seshid, all_sesh.sessions[seshid].Palettes.keys())
else:
print('getSesh--sesh in all_sesh: ', seshid, all_sesh.sessions[seshid].Palettes.keys())
sesh = all_sesh.sessions[seshid]
return sesh
def setSesh(seshid, sesh):
all_sesh.sessions[seshid] = sesh
default_img = np.zeros((200,200,3)).astype(np.uint8)
default_img[:] = 64
Palette_img = np.zeros((200,200,3)).astype(np.uint8)
Palette_img[:] = 128
def submitPhoto(img, rooms, seshid):
sesh = getSesh(seshid)
if sesh.seshid != seshid:
sesh.seshid = seshid
print('submitPhoto reset rooms: ', rooms, seshid, sesh.seshid)
sesh.current_img_signature = str(img.sum())
sesh.img_data[sesh.current_img_signature] = img
sesh.Palettes[sesh.current_img_signature] = {}
sesh.activated_items[sesh.current_img_signature] = {}
sesh.filtered_files[sesh.current_img_signature] = {}
sesh.filtered_files_room[sesh.current_img_signature] = {}
sesh.filtered_files_style[sesh.current_img_signature] = {}
sesh.frmt_idxs_maps[sesh.current_img_signature] = {}
sesh.frmt_id_maps[sesh.current_img_signature] = {}
sesh.Palette_img = np.zeros((200,200,3)).astype(np.uint8)
sesh.Palette_img[:] = 128
sesh.items_layouts[sesh.current_img_signature] = bed_layout_new
rooms = rooms if rooms else []
rooms.append((img, sesh.current_img_signature))
print('submitPhoto reset: ', sesh.reset)
#return [(v,str(k)) for k,v in sesh.img_data.items()], gr.Image(label='Upload Room Photo
setSesh(seshid, sesh)
return rooms, gr.Image(label='Upload Room Photo'), seshid
def summarisePerStore(seshid):
sesh = getSesh(seshid)
sesh.summary_joined = {}
for imgid,product_dicts in sesh.summary.items():
for item_pd in product_dicts:
if not item_pd:
continue
item, pd = item_pd[0], item_pd[1]
store = pd['store'].split(' -')[0]
if store and store not in sesh.summary_joined:
sesh.summary_joined[store] = {'total': 0, 'num_items':0, 'descriptions':[], 'prices':[], 'sources':[]}
sesh.summary_joined[store]['total'] += float(pd['price'].replace('$', '').replace(',', '')) if pd['price'] and '$' in pd['price'] else 0
sesh.summary_joined[store]['prices'].append(pd['price'] if pd['price'] and '$' in pd['price'] else None)
sesh.summary_joined[store]['descriptions'].append(pd['description'])
sesh.summary_joined[store]['sources'].append(pd['href'])
sesh.summary_joined[store]['num_items'] += 1
setSesh(seshid, sesh)
def summarisePerStore(seshid):
sesh = getSesh(seshid)
sesh.summary_joined = {}
for imgid,product_dicts in sesh.summary.items():
for item_pd in product_dicts:
if not item_pd:
continue
item, pd = item_pd[0], item_pd[1]
store = pd['store'].split(' -')[0]
if store and store not in sesh.summary_joined:
sesh.summary_joined[store] = {}
sesh.summary_joined[store][item] = {'product_dict': pd, 'count':1}
setSesh(seshid, sesh)
def updateItemDisplay(seshid, budget=False):
sesh = getSesh(seshid)
if True:
keys = ['filtered_items_room', 'current_img_signature', 'items', 'filtered_items_style', 'room_style', 'room_type', 'bedsize', 'price', 'filtered_items_colors', 'Palette_ids', 'item_data', 'item_data_', 'display_items', 'item_data_keys', 'Palettes_displayed', 'room_img_loaded', 'Paletteid', 'img_id', 'seshid']
url = 'https://dreamdemo.pythonanywhere.com/sesh'
data = sesh.__dict__
valid_data = {k:v for k,v in data.items() if k in keys}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
if True: #try:
import json
r = requests.post(url, data=json.dumps(valid_data), headers=headers)
print('json return status code: ', r.status_code)
data_dict = json.loads(r.content)
for k in data_dict:
print('setting attr: ', k)
setattr(sesh, k, data_dict[k])
if True:
#sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]] = {item:[d for d in products if ((not budget or not hasattr(sesh,'item_budgets') or sesh.current_img_signature not in sesh.item_budgets) or float(d['price'].replace('$', '').replace(',', ''))<sesh.item_budgets[sesh.current_img_signature][item])] for item,products in sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items()}
sesh.product_means[sesh.current_img_signature] = {item:sum([float(pd['price'].replace('$', '').replace(',', '')) for pd in products])/len(products) if products else 0 for item,products in sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items() if item not in ['Palette', 'Living Room', 'Bedroom']}
if hasattr(sesh, 'budget_number') and sesh.budget_number:
print('updateItemDisplay -- sesh.budget_number: ', sesh.budget_number)
#product_lens = {item:len(products) for item,products in sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items() if item not in ['Palette', 'Living Room', 'Bedroom']}
#print('updateItemDisplay -- product_lens: ', product_lens)
sesh.product_means_total = sum([v for img in sesh.product_means for k,v in sesh.product_means[img].items()])
sesh.product_means_weights = {img:{item:avg/sesh.product_means_total for item,avg in sesh.product_means[img].items()} for img in sesh.product_means}
print('updateItemDisplay -- sesh.product_means, sesh.product_means_total, sesh.product_means_weights, budget: ', sesh.product_means, sesh.product_means_total, sesh.product_means_weights, budget)
sesh.item_budgets = {img: {item: int(weight*sesh.budget_number) for item,weight in weights.items()} for img,weights in sesh.product_means_weights.items()}
#sesh.item_data_keys[sesh.current_img_signature] = {'room_type': sesh.room_type, 'room_style':sesh.room_style, 'price': sesh.price, 'Paletteid': sesh.Palette_ids[sesh.current_img_signature], 'inbudget':{item:[didx for didx,d in enumerate(products) if ((not budget or not hasattr(sesh,'item_budgets') or sesh.current_img_signature not in sesh.item_budgets) or float(d['price'].replace('$', '').replace(',', ''))<sesh.item_budgets[sesh.current_img_signature][item])] for item,products in sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items()}}
sesh.inbudget = {img:{item:[didx for didx,d in enumerate(products) if float(d['price'].replace('$', '').replace(',', ''))<sesh.item_budgets[img][item]] for item,products in sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']].items()} for img in sesh.item_data_keys}
sesh.display_items_ = {img:[(-1 if item in ['Palette', 'Living Room', 'Bedroom'] or not sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item] else (sesh.display_items_[img][itemi][0] if sesh.display_items_[img][itemi][0] in sesh.inbudget[img][item] else (-1 if not sesh.inbudget[img][item] else np.random.choice(sesh.inbudget[img][item]))), item) for itemi,item in enumerate(sesh.items_layouts[img])] for img in sesh.item_data_keys}
else:
#sesh.item_data_keys[sesh.current_img_signature] = {'room_type': sesh.room_type, 'room_style':sesh.room_style, 'price': sesh.price, 'Paletteid': sesh.Palette_ids[sesh.current_img_signature], 'inbudget':{item:[didx for didx,d in enumerate(products)] for item,products in sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items()}}
sesh.inbudget = {img:{item:[didx for didx,d in enumerate(products)] for item,products in sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']].items()} for img in sesh.item_data_keys}
#print('room type: ', [(sesh.item_data_keys[img]['room_type'], None if not hasattr(sesh, 'display_items_') else [data[0] for itemis,data in sesh.display_items_[img].items()],) for img in sesh.item_data_keys])
print('room type: ', [sesh.item_data_keys[img]['room_type'] for img in sesh.item_data_keys])
#sesh.display_items_ = {img:[(-1 if item in ['Palette', 'Living Room', 'Bedroom'] or not sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item] else (sesh.display_items_[img][itemi][0] if hasattr(sesh, 'display_items_') and img in sesh.display_items_ and itemi in sesh.display_items_[img] and sesh.display_items_[img][itemi] and sesh.display_items_[img][itemi][0] in sesh.inbudget[img][item] else random.sample(list(range(len(sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item]))), 1)[0]), item) for itemi,item in enumerate(sesh.items_layouts[img])] for img in sesh.item_data_keys}
sesh.display_items_ = {img:[(-1 if item in ['Palette', 'Living Room', 'Bedroom'] or not sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item] else (random.sample(list(range(len(sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item]))), 1)[0]), item) for itemi,item in enumerate(sesh.items_layouts[img])] for img in sesh.item_data_keys}
if hasattr(sesh, 'budget_number') and sesh.budget_number:
print('updateDisplay -- sesh.item_budgets: ', sesh.item_budgets, sum([v for img in sesh.item_budgets for k,v in sesh.item_budgets[img].items()]))
sesh.summary = {img: [() if itemidx_item[1] in ['Palette', 'Living Room', 'Bedroom'] or itemidx_item[0] < 0 else (itemidx_item[1], sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][itemidx_item[1]][itemidx_item[0]]) for itemidx_item in sesh.display_items_[img]] for img in sesh.display_items_}
realised_display = [((sesh.Palette_imgs[sesh.current_img_signature] if item_dataidx[1] == 'Palette' else sesh.img_data[sesh.img_id]) if item_dataidx[1] in ['Palette', 'Living Room', 'Bedroom'] else (sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][item_dataidx[1]][item_dataidx[0]]['img'] if item_dataidx[0] >= 0 else sesh.default_img), item_dataidx[1]) for item_dataidx in sesh.display_items_[sesh.current_img_signature]]
#print('writing For Store Processing')
for item_dataidx in sesh.display_items_[sesh.current_img_signature]:
if item_dataidx[0] >= 0:
store = sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][item_dataidx[1]][item_dataidx[0]]['store']
writeForStoreProcessing(store, sesh.zipcode)
#print('wrote For Store Processing: ', store)
#print('completed writing For Store Processing')
sesh.updated_display = realised_display
summarisePerStore(seshid)
setSesh(seshid, sesh)
return gr.Gallery(realised_display, label='Room Items', columns=5)
else: #except:
setSesh(seshid, sesh)
return sesh.updated_display
def getMostUsedColorsRGB(img_bytes):
if True:
img = np.array(Image.open(io.BytesIO(img_bytes)))
else:
return []
imgq = img // 48 * 48
clr_counts = {}
for i in range(0, imgq.shape[0], 7):
for j in range(0, imgq.shape[1], 7):
clr = tuple(imgq[i,j])
if clr not in clr_counts:
clr_counts[clr] = 0
clr_counts[clr] += 1
clr_counts_ = {v:k for k,v in clr_counts.items()}
counts_srtd = sorted(clr_counts_)[::-1]
counts_srtd_rgb = [[int(val) for val in clr_counts_[i]] for i in counts_srtd[:7]]
return counts_srtd_rgb
def bytesToSerializableImageVals(img_bytes):
if True:
img = np.array(Image.open(io.BytesIO(img_bytes)).resize((35,35)))
#data = [tuple([int(val) for val in rgb]) for row in img for rgb in row]
data = [int(val) for row in img for rgb in row for val in rgb]
print('bytesToSerializableImageVals len+: ', len(data))
return data
else:
return []
def isJSONSerialiazable(obj):
try:
json.dumps(obj)
return True
except:
return False
def updateItemDisplay(seshid, budget=False, pallete_change=False):
sesh = getSesh(seshid)
print('updateItemDisplay seshid: ', seshid, sesh.seshid)
print('updateItemDisplay sesh.Palettes.keys: ', sesh.Palettes.keys())
print('updateItemDisplay all_sesh.sessions: ', all_sesh.sessions.keys())
if True:
keys = ['filtered_items_room', 'current_img_signature', 'items', 'filtered_items_style', 'room_style', 'room_type', 'bedsize', 'price', 'filtered_items_colors', 'Palette_ids', 'item_data', 'item_data_', 'display_items', 'item_data_keys', 'Palettes_displayed', 'room_img_loaded', 'Paletteid', 'img_id', 'seshid']
url = 'https://dreamdemo.pythonanywhere.com/sesh'
data = sesh.__dict__
valid_data = {k:v for k,v in data.items() if k in keys and isJSONSerialiazable(v)}
print('updateItemDisplay sesh keys: ', valid_data.keys())
valid_data['seshid'] = seshid
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
if True: #try:
print('new and improved updateDisplay -- Palette_ids, Paletteid: ', sesh.Palette_ids, sesh.Paletteid)
import json
r = requests.post(url, data=json.dumps(valid_data), headers=headers)
print('json return status code: ', r.status_code)
data_dict = json.loads(r.content)
#print('json return item_data_: ', data_dict['item_data_'])
for k in data_dict:
if k == 'seshid': continue
print('setting attr: ', k)
setattr(sesh, k, data_dict[k])
if True:
#sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]] = {item:[d for d in products if ((not budget or not hasattr(sesh,'item_budgets') or sesh.current_img_signature not in sesh.item_budgets) or float(d['price'].replace('$', '').replace(',', ''))<sesh.item_budgets[sesh.current_img_signature][item])] for item,products in sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items()}
sesh.product_means[sesh.current_img_signature] = {item:sum([float(pd['price'].replace('$', '').replace(',', '')) for pd in products])/len(products) if products else 0 for item,products in sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items() if item not in ['Palette', 'Living Room', 'Bedroom']}
if hasattr(sesh, 'budget_number') and sesh.budget_number and not pallete_change:
print('updateItemDisplay -- sesh.budget_number: ', sesh.budget_number)
#product_lens = {item:len(products) for item,products in sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items() if item not in ['Palette', 'Living Room', 'Bedroom']}
#print('updateItemDisplay -- product_lens: ', product_lens)
sesh.product_means_total = sum([v for img in sesh.product_means for k,v in sesh.product_means[img].items()])
sesh.product_means_weights = {img:{item:avg/sesh.product_means_total for item,avg in sesh.product_means[img].items()} for img in sesh.product_means}
print('updateItemDisplay -- sesh.product_means, sesh.product_means_total, sesh.product_means_weights, budget: ', sesh.product_means, sesh.product_means_total, sesh.product_means_weights, budget)
sesh.item_budgets = {img: {item: int(weight*sesh.budget_number) for item,weight in weights.items()} for img,weights in sesh.product_means_weights.items()}
#sesh.item_data_keys[sesh.current_img_signature] = {'room_type': sesh.room_type, 'room_style':sesh.room_style, 'price': sesh.price, 'Paletteid': sesh.Palette_ids[sesh.current_img_signature], 'inbudget':{item:[didx for didx,d in enumerate(products) if ((not budget or not hasattr(sesh,'item_budgets') or sesh.current_img_signature not in sesh.item_budgets) or float(d['price'].replace('$', '').replace(',', ''))<sesh.item_budgets[sesh.current_img_signature][item])] for item,products in sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items()}}
sesh.inbudget = {img:{item:[didx for didx,d in enumerate(products) if float(d['price'].replace('$', '').replace(',', ''))<sesh.item_budgets[img][item]] for item,products in sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']].items()} for img in sesh.item_data_keys}
sesh.display_items_ = {img:[(-1 if item in ['Palette', 'Living Room', 'Bedroom'] or not sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item] else (sesh.display_items_[img][itemi][0] if sesh.display_items_[img][itemi][0] in sesh.inbudget[img][item] else (-1 if not sesh.inbudget[img][item] else np.random.choice(sesh.inbudget[img][item]))), item) for itemi,item in enumerate(sesh.items_layouts[img])] for img in sesh.item_data_keys}
else:
#sesh.item_data_keys[sesh.current_img_signature] = {'room_type': sesh.room_type, 'room_style':sesh.room_style, 'price': sesh.price, 'Paletteid': sesh.Palette_ids[sesh.current_img_signature], 'inbudget':{item:[didx for didx,d in enumerate(products)] for item,products in sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items()}}
sesh.inbudget = {img:{item:[didx for didx,d in enumerate(products)] for item,products in sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']].items()} for img in sesh.item_data_keys}
#print('room type: ', [(sesh.item_data_keys[img]['room_type'], None if not hasattr(sesh, 'display_items_') else [data[0] for itemis,data in sesh.display_items_[img].items()],) for img in sesh.item_data_keys])
print('room type: ', [sesh.item_data_keys[img]['room_type'] for img in sesh.item_data_keys])
#sesh.display_items_ = {img:[(-1 if item in ['Palette', 'Living Room', 'Bedroom'] or not sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item] else (sesh.display_items_[img][itemi][0] if hasattr(sesh, 'display_items_') and img in sesh.display_items_ and itemi in sesh.display_items_[img] and sesh.display_items_[img][itemi] and sesh.display_items_[img][itemi][0] in sesh.inbudget[img][item] else random.sample(list(range(len(sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item]))), 1)[0]), item) for itemi,item in enumerate(sesh.items_layouts[img])] for img in sesh.item_data_keys}
item_lens = [(item, len(sesh.item_data[sesh.current_img_signature][sesh.item_data_keys[sesh.current_img_signature]['room_type']][sesh.item_data_keys[sesh.current_img_signature]['room_style']][sesh.item_data_keys[sesh.current_img_signature]['price']][sesh.item_data_keys[sesh.current_img_signature]['Paletteid']][item])) for itemi,item in enumerate(sesh.items_layouts[sesh.current_img_signature])]
getSampleIndexes = lambda lngth: sorted(set([int(i) for j in [2,3,4] for i in [np.clip(0,lngth-1,lngth//j), np.clip(0,lngth-1,lngth-(lngth//j))]] + [0,(lngth-1 if lngth > 0 else 0)]))
item_idxs = [(pair[0], [] if pair[1] <= 0 else getSampleIndexes(pair[1])) for pair in item_lens]
item_lens_ln = [len(pair[1]) for pair in item_idxs]
urls = [sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][pair[0]][idx]['img'] for i,pair in enumerate(item_idxs) if pair[1] for idx in pair[1]]
start = time.time()
responses = asyncio.run(main(urls))
#rgbs = [getMostUsedColorsRGB(r) for r in responses]
print('number of images retrieved: ', len(responses), item_lens)
pallete_rgb = list(set([tuple([int(val) for val in rgb]) for row in sesh.Palette_img for rgb in row]))
"""url = 'https://dreamdemo.pythonanywhere.com/rgb'
valid_data = {'rgbs':rgbs, 'pallete_rgb':pallete_rgb}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(valid_data), headers=headers)
jsondata = json.loads(r.content)
scores = jsondata['data']"""
start = time.time()
urls = ['https://dreamdemo.pythonanywhere.com/overlap' for i,_ in enumerate(responses)]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
#json_data = [json.dumps({'pallete_rgb': pallete_rgb, 'item_rgb':bytesToSerializableImageVals(r)}) for i,r in enumerate(responses)]
end = time.time()
print('bytesToSerializableImageVals: ', end-start)
start = time.time()
"""try:
responses = asyncio.run(main_post(urls[:3], headers[:3], json_data[:3], timeout=.5))
responses = asyncio.run(main_post(urls, headers, json_data, timeout=5))
scores_ = [json.loads(r)['data'] for r in responses]
#print('overlap scores: ', scores[:20])
except:
scores_ = [0 for i,_ in enumerate(urls)]"""
scores_ = [0 for i,_ in enumerate(urls)]
end = time.time()
scores = scores_ #[scores_[i%7] if i%7==0 else 0 for i,_ in enumerate(item_lens_ln)]
print('bytesToSerializableImageVals overlap: ', end-start, scores[:10])
section_scores = [scores[sum(item_lens_ln[:i]):sum(item_lens_ln[:i])+ln] for i,ln in enumerate(item_lens_ln)]
section_scores_amax = [np.argmax(s) if s else -1 for s in section_scores]
#section_scores_amax = [np.argsort(s)[::-1][np.random.randint(0,max(3, len(s)-1))] if len(s) < 2 else -1 for s in section_scores]
best_idxs = {item_idxs[i][0]: item_idxs[i][1][idx] if idx > -1 else -1 for i,idx in enumerate(section_scores_amax)}
end = time.time()
print('updateDisplay -- item images downloaded: ', str(end-start), best_idxs)
#sesh.display_items_ = {img:[(-1 if item in ['Palette', 'Living Room', 'Bedroom'] or not sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item] else (random.sample(list(range(len(sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item]))), 1)[0]), item) for itemi,item in enumerate(sesh.items_layouts[img])] for img in sesh.item_data_keys}
sesh.display_items_ = {img:[(-1 if item in ['Palette', 'Living Room', 'Bedroom'] or not sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item] else (random.sample(list(range(len(sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][item]))), 1)[0] if img != sesh.current_img_signature else best_idxs[item]), item) for itemi,item in enumerate(sesh.items_layouts[img])] for img in sesh.item_data_keys}
if hasattr(sesh, 'budget_number') and sesh.budget_number:
print('updateDisplay -- sesh.item_budgets: ', sesh.item_budgets, sum([v for img in sesh.item_budgets for k,v in sesh.item_budgets[img].items()]))
sesh.summary = {img: [() if itemidx_item[1] in ['Palette', 'Living Room', 'Bedroom'] or itemidx_item[0] < 0 else (itemidx_item[1], sesh.item_data[img][sesh.item_data_keys[img]['room_type']][sesh.item_data_keys[img]['room_style']][sesh.item_data_keys[img]['price']][sesh.item_data_keys[img]['Paletteid']][itemidx_item[1]][itemidx_item[0]]) for itemidx_item in sesh.display_items_[img]] for img in sesh.display_items_}
realised_display = [((sesh.Palette_imgs[sesh.current_img_signature] if item_dataidx[1] == 'Palette' else sesh.img_data[sesh.img_id]) if item_dataidx[1] in ['Palette', 'Living Room', 'Bedroom'] else (sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][item_dataidx[1]][item_dataidx[0]]['img'] if item_dataidx[0] >= 0 else sesh.default_img), item_dataidx[1]) for item_dataidx in sesh.display_items_[sesh.current_img_signature]]
#print('writing For Store Processing')
for item_dataidx in sesh.display_items_[sesh.current_img_signature]:
if item_dataidx[0] >= 0:
store = sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][item_dataidx[1]][item_dataidx[0]]['store']
writeForStoreProcessing(store, sesh.zipcode)
#print('wrote For Store Processing: ', store)
#print('completed writing For Store Processing')
sesh.updated_display = realised_display
summarisePerStore(seshid)
"""sesh.product_pd_counts = [(product,pd_count) for store in sesh.summary_joined for product,pd_count in sesh.summary_joined[store].items()]
urls = [product_pd_count[1]['product_dict']['href'] for product_pd_count in sesh.product_pd_counts]
sesh.responses = asyncio.run(main(urls))
item_locator_data = {data[1]: sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']}
print('item_locator_data: ', item_locator_data, '\n/*/*', [item_locator_data[product_pd_count[0]] for i,product_pd_count in enumerate(sesh.product_pd_counts)])
responses = [r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses]
urls = ['https://dreamdemo.pythonanywhere.com/dump_text_gen' for _ in range(len(sesh.product_pd_counts))]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
for item,idxs in item_locator_data.items():
if tuple(idxs) not in sesh.locator_genid: sesh.locator_genid[tuple(idxs)] = gen_uid = str(time.time())
json_data = [json.dumps({'room_type': sesh.room_type, 'item_locator_data': item_locator_data[product_pd_count[0]], 'gen_uid': sesh.locator_genid[tuple(item_locator_data[product_pd_count[0]])], 'response':responses[i], 'item': product_pd_count[0]}) for i,product_pd_count in enumerate(sesh.product_pd_counts) if product_pd_count[0] not in ['Palette', 'Living Room', 'Bedroom']]
responses = asyncio.run(main_post(urls, headers, json_data, timeout=.1))
print('dump_text_gen: ', responses)"""
"""item_locator_data = content['item_locator_data']
responses = content['responses']
items = content['items']
number_of_items = min(max(content['number_of_items'], 3), 7)
room_type = content['room_type']
video_format = content['video_format']"""
"""urls = [sesh.item_data[sesh.current_img_signature][sesh.item_data_keys[sesh.current_img_signature]['room_type']][sesh.item_data_keys[sesh.current_img_signature]['room_style']][sesh.item_data_keys[sesh.current_img_signature]['price']][sesh.item_data_keys[sesh.current_img_signature]['Paletteid']][itemidx_item[1]][itemidx_item[0]]['href'] for itemidx_item in sesh.display_items_[sesh.current_img_signature] if itemidx_item[1] not in ['Palette', 'Living Room', 'Bedroom']]
sesh.responses = asyncio.run(main(urls))
urls = ['https://dreamdemo.pythonanywhere.com/store_shop' for _ in range(len(urls))]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
responses = [r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses]
item_locator_data = [sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']]
json_data = [json.dumps({'response': responses[i], 'item_locator_data': item_locator_data[i]}) for i,url in enumerate(urls)]
responses = asyncio.run(main_post(urls, headers, json_data, timeout=.5))
print('*-/*/-*-updateDisplay: dumped store_shop: ', item_locator_data)
formats = ['Youtube Long-Form', 'Youtube Short-Form', 'Facebook Long-Form', 'Instagram Reel', 'Tiktok', 'LinkedIn']
number_of_items = [7, 3, 7, 3, 3, 7]
urls = [sesh.item_data[sesh.current_img_signature][sesh.item_data_keys[sesh.current_img_signature]['room_type']][sesh.item_data_keys[sesh.current_img_signature]['room_style']][sesh.item_data_keys[sesh.current_img_signature]['price']][sesh.item_data_keys[sesh.current_img_signature]['Paletteid']][itemidx_item[1]][itemidx_item[0]]['href'] for itemidx_item in sesh.display_items_[sesh.current_img_signature] if itemidx_item[1] not in ['Palette', 'Living Room', 'Bedroom']]
sesh.responses = asyncio.run(main(urls))
urls = ['https://dreamdemo.pythonanywhere.com/scriptgen_promise' for _ in range(len(formats))]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
responses = [[r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses] for _ in range(len(formats))]
item_locator_data = [[sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']] for _ in range(len(formats))]
items = [[data[1] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']] for _ in range(len(formats))]
idxs = [list(range(len(items))) for i,_ in enumerate(formats)]
for i,_ in enumerate(formats):
np.random.shuffle(idxs[i])
idxs[i] = idxs[i][:number_of_items[i]]
sesh.frmt_idxs_maps[sesh.current_img_signature][formats[i]] = [item_locator_data[i][idx] for idx in idxs[i]]
sesh.frmt_id_maps[sesh.current_img_signature][formats[i]] = str(time.time())
time.sleep(.001)
#json_data = [json.dumps({'video_format': fmt, 'number_of_items': number_of_items[i], 'room_type': sesh.room_type, 'item_locator_data': item_locator_data, 'gen_uid': i, 'responses':responses, 'items': items}) for i,fmt in enumerate(formats)]
json_data = [json.dumps({'video_format': fmt, 'number_of_items': number_of_items[i], 'idxs':idxs[i][:number_of_items[i]], 'room_type': sesh.room_type, 'item_locator_data': item_locator_data[i], 'gen_uid': sesh.frmt_id_maps[sesh.current_img_signature][formats[i]], 'seshid':seshid, 'items': items[i]}) for i,fmt in enumerate(formats)]
responses = asyncio.run(main_post(urls, headers, json_data, timeout=.5))
#responses = asyncio.run(main_post(urls, headers, json_data, timeout=3))
print('*-/*/-*-updateDisplay: dumped scriptgen_promise: ', responses)"""
setSesh(seshid, sesh)
return gr.Gallery(realised_display, label='Room Items', columns=5)
else: #except:
setSesh(seshid, sesh)
return sesh.updated_display
def updateRoomType(evt: gr.SelectData, seshid):
sesh = getSesh(seshid)
label = evt.value['caption'].lower().split()[0] if evt.value['caption'] else sesh.room_type
sesh.room_type = label
images = [(v['bedroom'] if sesh.room_type == 'bedroom' else v['living room'], k) for k,v in styles_images.items()]
sesh.items = items = bed_layout_new if sesh.room_type == 'bedroom' else living_layout_new
sesh.items_layouts[sesh.current_img_signature] = items = bed_layout_new if sesh.room_type == 'bedroom' else living_layout_new
#display = updateItemDisplay()
if hasattr(sesh, 'room_img_loaded') and sesh.room_img_loaded:
display = updateItemDisplay(seshid)
else:
display = sesh.updated_display
setSesh(seshid, sesh)
return images, gr.Radio(['Full', 'Queen', 'King'], value='Full', label='Bed Size', interactive=True, visible=True) if label == 'bedroom' else gr.Radio(visible=False), gr.Gallery(sesh.updated_display, label='Room Items', columns=5), display
def updateStyle(evt: gr.SelectData, seshid):
sesh = getSesh(seshid)
style = evt.value['caption'].lower().split()[0] if evt.value['caption'] else sesh.room_style
sesh.room_style = style
if hasattr(sesh, 'room_img_loaded') and sesh.room_img_loaded:
display = updateItemDisplay(seshid)
setSesh(seshid, sesh)
return display
else:
setSesh(seshid, sesh)
return sesh.updated_display
def updatePrice(evt: gr.SelectData, seshid):
sesh = getSesh(seshid)
print('updatePrice: ', type(evt.value), evt.value)
price = evt.value if evt.value else sesh.price
sesh.price = price
if hasattr(sesh, 'room_img_loaded') and sesh.room_img_loaded:
display = updateItemDisplay(seshid)
setSesh(seshid, sesh)
return display
else:
setSesh(seshid, sesh)
return sesh.updated_display
def updateBedsize(evt: gr.SelectData, seshid):
sesh = getSesh(seshid)
bedsize = evt.value if evt.value else sesh.bedsize
sesh.bedsize = bedsize
if hasattr(sesh, 'room_img_loaded') and sesh.room_img_loaded:
display = updateItemDisplay(seshid)
setSesh(seshid, sesh)
return display
else:
setSesh(seshid, sesh)
return sesh.updated_display
#sesh.palettes_data
def updateColors(evt: gr.SelectData, seshid):
sesh = getSesh(seshid)
Paletteid = evt.value['caption'] if evt.value['caption'] else '0'
sesh.Paletteid = evt.value['caption']
sesh.Palette_ids[sesh.current_img_signature] = Paletteid
sesh.Palette_img = np.zeros((200,200,3)).astype(np.uint8)
sesh.Palette_img[:50,:] = sesh.palettes_data[sesh.Paletteid][0]
sesh.Palette_img[50:100,:] = sesh.palettes_data[sesh.Paletteid][1]
sesh.Palette_img[100:150,:] = sesh.palettes_data[sesh.Paletteid][2]
sesh.Palette_img[150:,:] = sesh.palettes_data[sesh.Paletteid][3]
sesh.Palette_imgs[sesh.img_id] = sesh.Palette_img
if hasattr(sesh, 'room_img_loaded') and sesh.room_img_loaded:
display = updateItemDisplay(seshid, pallete_change=True)
setSesh(seshid, sesh)
return display
else:
setSesh(seshid, sesh)
return sesh.updated_display
#Palettes_displayed, Palettes
def makePalettes(evt: gr.SelectData, seshid):
sesh = getSesh(seshid)
print('makePalettes called: ', seshid, sesh.seshid, sesh.Palettes_displayed.keys())
sesh.img_id = sesh.current_img_signature = evt.value['caption'] if evt.value['caption'] else sesh.current_img_signature
if sesh.current_img_signature in sesh.Palettes_displayed:
print('makePalettes img found: ', seshid, sesh.seshid)
print('makePalettes img sig in sesh.Palettes_displayed--updating and returning: ', evt.value['caption'], sesh.current_img_signature, sesh.img_id, sesh.Palettes_displayed.keys())
display = updateItemDisplay(seshid)
return sesh.Palettes_displayed[sesh.current_img_signature], sesh.img_data[sesh.current_img_signature], display
print('makePalettes check1: ')
img = sesh.img_data[sesh.img_id]
imgq = img // 48 * 48
Palette_out = []
Palette_accounting = []
clr_counts = {}
for i in range(imgq.shape[0]):
for j in range(imgq.shape[1]):
clr = tuple(imgq[i,j])
if clr not in clr_counts:
clr_counts[clr] = 0
clr_counts[clr] += 1
clr_counts_ = {v:k for k,v in clr_counts.items()}
counts_srtd = sorted(clr_counts_)[::-1]
#counts_srtd_rgb = [clr_counts_[i] for i in counts_srtd[:4]]
counts_srtd_rgb = [[int(val) for val in clr_counts_[i]] for i in counts_srtd[:4]]
#bestclr_keys = [color_maps[color_maps_keys[getBestMatch(color_maps_keys, rgb)]] for rgb in counts_srtd_rgb]
dark_light_bool = int(np.sum(counts_srtd_rgb)//12//128)
Palettes = {}
i = 0
print('makePalettes check2: ')
#print('bestclr_keys: ', bestclr_keys)
url = 'https://dreamdemo.pythonanywhere.com/palletes'
#valid_data = {'seshid': str(sesh.seshid), 'img_id':str(sesh.img_id), 'dark_light_bool':str(dark_light_bool), 'bestclr_keys':bestclr_keys}
#valid_data = {'seshid': str(sesh.seshid), 'img_id':str(sesh.img_id), 'dark_light_bool':str(dark_light_bool), 'counts_srtd_rgb':counts_srtd_rgb}
valid_data = {'seshid': str(seshid), 'img_id':str(sesh.img_id), 'dark_light_bool':str(dark_light_bool), 'counts_srtd_rgb':counts_srtd_rgb}
#print('MAKE PALLETE SESHID: ', seshid, sesh.seshid)
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
#print('json requests response: ', str({k:(type(v), None if type(v) != type(dict({})) or not v else (type(list(v.items())[0][0]), type(list(v.items())[0][1]))) for k,v in valid_data.items()}))
#print('json requests response: ', str({k:(type(v), None if type(v) != type(dict({})) or not v else (type(list(v.items())[0][0]), type(list(v.items())[0][1]))) for k,v in data.items()}))
r = requests.post(url, data=json.dumps(valid_data), headers=headers)
#jsondata = r.json()
jsondata = json.loads(r.content)
print('makePalettes img sig was not in sesh.Palettes_displayed: ', sesh.Palettes_displayed.keys())
#print('\npalette json requests response: ', str(r.content), '\njson data: ', jsondata )
print('makePalettes check3: ')
Palette_out = []
palettes_data = [cdata[0] for cdata in jsondata['got']]
gcounts = [sum([c[1] for c in cdata]) for cdata in palettes_data]
gsrt = np.argsort(gcounts)[::-1]
palettes_data = [palettes_data[i] for i in gsrt]
sesh.palettes_data = {str(idx+1):cdata for idx,cdata in enumerate(palettes_data)}
#print('palettes_data: ', type(palettes_data), palettes_data)
for idx,cdata in enumerate(palettes_data):
newimg = np.zeros((200,200,3))
newimg[:50,:] = cdata[0]
newimg[50:100,:] = cdata[1]
newimg[100:150,:] = cdata[2]
newimg[150:,:] = cdata[3]
Palette_out.append((newimg.astype(np.uint8), str(idx+1)))
sesh.Paletteid = '1' #str(len(palettes_data)-1)
sesh.Palette_ids[sesh.current_img_signature] = sesh.Paletteid
sesh.Palette_img = np.zeros((200,200,3)).astype(np.uint8)
sesh.Palette_img[:50,:] = palettes_data[0][0]
sesh.Palette_img[50:100,:] = palettes_data[0][1]
sesh.Palette_img[100:150,:] = palettes_data[0][2]
sesh.Palette_img[150:,:] = palettes_data[0][3]
sesh.Palette_imgs[sesh.img_id] = sesh.Palette_img
display = updateItemDisplay(seshid)
print('makePalettes check4: ')
sesh.Palettes_displayed[sesh.current_img_signature] = Palette_out
sesh.room_img_loaded = True
setSesh(seshid, sesh)
return Palette_out, sesh.img_data[sesh.img_id], display
#directory
def set_Palette(evt: gr.SelectData, seshid):
sesh = getSesh(seshid)
sesh.Paletteid = evt.value['caption']
sesh.Palette_img = np.zeros((200,200,3)).astype(np.uint8)
sesh.Palette_img[:50,:] = sesh.Palettes[sesh.img_id][sesh.Paletteid][0][0]
sesh.Palette_img[50:100,:] = sesh.Palettes[sesh.img_id][sesh.Paletteid][0][1]
sesh.Palette_img[100:150,:] = sesh.Palettes[sesh.img_id][sesh.Paletteid][0][2]
sesh.Palette_img[150:,:] = sesh.Palettes[sesh.img_id][sesh.Paletteid][0][3]
sesh.Palette_imgs[sesh.img_id] = sesh.Palette_img
sesh.Palette_ids[sesh.img_id] = sesh.Paletteid
setSesh(seshid, sesh)
def set_style(evt: gr.SelectData, seshid):
sesh = getSesh(seshid)
label = evt.value['caption'].lower().split()[0]
sesh.room_type = label
images = [(v['bedroom'] if label == 'bedroom' else v['living room'], k) for k,v in styles_images.items()]
sesh.items = items = bed_layout_new if label == 'bedroom' else living_layout_new
print('set_style: ', items)
sesh.filtered_files_room[sesh.img_id] = {color: [f for f in cfiles if any([(lambda substrs, f: substrs and substrs[0].lower() in f.lower() and (len(substrs)==1 or substrs[1] in f.lower()))(item.replace('-', ' ').split(), f) for item in items])] for color,cfiles in sesh.filtered_files[sesh.img_id].items()}
room_items_imgs_tuples = [((sesh.Palette_img if item == 'Palette' else sesh.img_data[sesh.img_id]) if item in ['Palette', 'Living Room', 'Bedroom'] else room_item_placeholder_images_dict['BEDROOM FURNITURE' if label == 'bedroom' else 'LIVING ROOM FURNITURE'][item], item) for item in items]
setSesh(seshid, sesh)
return images, gr.Radio(['Full', 'Queen', 'King'], value='Full', label='Bed Size', interactive=True, visible=True) if label == 'bedroom' else gr.Radio(visible=False), gr.Gallery(room_items_imgs_tuples, label='Room Items', columns=5)
def applyStyle(evt: gr.SelectData, seshid):
sesh = getSesh(seshid)
design_style = evt.value['caption'].lower().split()[0]
sesh.filtered_files_style[sesh.img_id] = {color: [f for f in cfiles if any([(lambda substrs, f: substrs and substrs[0].lower() in f.lower() and (len(substrs)==1 or substrs[1] in f.lower()))(substr.replace('-', ' ').split(), f) for substr in design_style.split()])] for color,cfiles in sesh.filtered_files_room[sesh.img_id].items()}
room_items_imgs_tuples = []
for item in sesh.items:
for color,cfiles in sesh.filtered_files_style[sesh.img_id].items():
for f in cfiles:
if item.split()[-1].lower() in f:
if item not in sesh.activated_items[str(img.sum())]:
sesh.activated_items[sesh.img_id][item] = []
with open(directory+f, 'r') as openfile:
data = json.load(openfile)
sesh.activated_items[sesh.img_id][item] += data
room_items_imgs_tuples = [((sesh.Palette_img if item == 'Palette' else sesh.img_data[sesh.img_id]) if item in ['Palette', 'Living Room', 'Bedroom'] else room_item_placeholder_images_dict['BEDROOM FURNITURE' if sesh.room_type == 'bedroom' else 'LIVING ROOM FURNITURE'][item], item) for item in sesh.items]
setSesh(seshid, sesh)
return gr.Gallery(room_items_imgs_tuples, label='Room Items', columns=5)
def uploadToScriptGenPromise(frmt, seshid):
sesh = getSesh(seshid)
if True:
formats = ['Youtube Long-Form', 'Youtube Short-Form', 'Facebook Long-Form', 'Instagram Reel', 'Tik Tok', 'LinkedIn']
#formats = [frmt]
number_of_items = [7, 3, 7, 3, 3, 7]
urls = [sesh.item_data[sesh.current_img_signature][sesh.item_data_keys[sesh.current_img_signature]['room_type']][sesh.item_data_keys[sesh.current_img_signature]['room_style']][sesh.item_data_keys[sesh.current_img_signature]['price']][sesh.item_data_keys[sesh.current_img_signature]['Paletteid']][itemidx_item[1]][itemidx_item[0]]['href'] for itemidx_item in sesh.display_items_[sesh.current_img_signature] if itemidx_item[1] not in ['Palette', 'Living Room', 'Bedroom']]
#urls = ['https://dreamdemo.pythonanywhere.com/scriptgen_promise' for _ in range(len(formats))]
#headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
item_locator_data = [[sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']] for _ in range(len(formats))]
items = [[data[1] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']] for _ in range(len(formats))]
idxs = [list(range(len(items[0]))) for i,_ in enumerate(formats)]
process = {}
print('*-/*/-*-DDSDSDSSD roomItemClick: scriptgen_promise items : ', items[0], idxs[0])
for i,_ in enumerate(formats):
if formats[i] != frmt or (formats[i] in sesh.frmt_idxs_maps[sesh.current_img_signature] and all([tupe in item_locator_data[0] for tupe in sesh.frmt_idxs_maps[sesh.current_img_signature][formats[i]]])):
process[i] = False
continue
np.random.shuffle(idxs[i])
print('*-/*/-*-DDSDSDSSD roomItemClick: scriptgen_promise number_of_items 1: ', formats[i], frmt, number_of_items[i], idxs[i])
idxs[i] = idxs[i][:number_of_items[i]]
sesh.frmt_idxs_maps[sesh.current_img_signature][formats[i]] = [item_locator_data[i][idx] for idx in idxs[i]]
sesh.frmt_id_maps[sesh.current_img_signature][formats[i]] = str(time.time())
process[i] = True
time.sleep(.001)
print('*-/*/-*-DDSDSDSSD roomItemClick: scriptgen_promise number_of_items 2: ', number_of_items[i], idxs[i])
#json_data = [json.dumps({'video_format': fmt, 'number_of_items': number_of_items[i], 'room_type': sesh.room_type, 'item_locator_data': item_locator_data, 'gen_uid': i, 'responses':responses, 'items': items}) for i,fmt in enumerate(formats)]
#json_data = [json.dumps({'video_format': fmt, 'number_of_items': number_of_items[i], 'idxs':idxs[i][:number_of_items[i]], 'room_type': sesh.room_type, 'item_locator_data': item_locator_data[i], 'gen_uid': sesh.frmt_id_maps[sesh.current_img_signature][formats[i]], 'seshid':seshid, 'items': items[i]}) for i,fmt in enumerate(formats) if process[i]]
json_data = [json.dumps({'video_format': fmt, 'number_of_items': number_of_items[i], 'idxs':idxs[i], 'room_type': sesh.room_type, 'item_locator_data': item_locator_data[i], 'gen_uid': sesh.frmt_id_maps[sesh.current_img_signature][formats[i]], 'seshid':seshid, 'items': items[i]}) for i,fmt in enumerate(formats) if process[i]]
if not json_data:
setSesh(seshid, sesh)
return
urls = ['https://dreamdemo.pythonanywhere.com/scriptgen_promise' for i in range(len(formats)) if process[i]]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(formats) if process[i]]
print('*-/*/-*-roomItemClick -- processed: ', len(json_data), [(f,process[i], idxs[i]) for i,f in enumerate(formats)])
responses = asyncio.run(main_post(urls, headers, json_data, timeout=.5))
#responses = asyncio.run(main_post(urls, headers, json_data, timeout=3))
print('*-/*/-*-roomItemClick: dumped scriptgen_promise: ', responses)
setSesh(seshid, sesh)
def uploadStoreShop(seshid):
sesh = getSesh(seshid)
if True:
urls = [sesh.item_data[sesh.current_img_signature][sesh.item_data_keys[sesh.current_img_signature]['room_type']][sesh.item_data_keys[sesh.current_img_signature]['room_style']][sesh.item_data_keys[sesh.current_img_signature]['price']][sesh.item_data_keys[sesh.current_img_signature]['Paletteid']][itemidx_item[1]][itemidx_item[0]]['href'] for itemidx_item in sesh.display_items_[sesh.current_img_signature] if itemidx_item[1] not in ['Palette', 'Living Room', 'Bedroom']]
sesh.responses = asyncio.run(main(urls))
urls = ['https://dreamdemo.pythonanywhere.com/store_shop' for _ in range(len(urls))]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
responses = [r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses]
item_locator_data = [sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']]
json_data = [json.dumps({'response': responses[i], 'item_locator_data': item_locator_data[i]}) for i,url in enumerate(urls)]
responses = asyncio.run(main_post(urls, headers, json_data, timeout=.5))
setSesh(seshid, sesh)
def roomItemClick(evt: gr.SelectData, seshid):
sesh = getSesh(seshid)
if 'SESHID' in all_sesh.sessions:
del all_sesh.sessions['SESHID']
selection = evt.value['caption'].lower()
seshidtype = '...'+str(type(seshid))+ '...'
seshid_ = '...'+str(seshid)+ '...'
seshid = str(time.time()) if not seshid or seshid == 'SESHID' else seshid
sesh.clicked_displayed_product = evt.value['caption']
setSesh(seshid, sesh)
if selection == 'palette':
"""urls = [sesh.item_data[sesh.current_img_signature][sesh.item_data_keys[sesh.current_img_signature]['room_type']][sesh.item_data_keys[sesh.current_img_signature]['room_style']][sesh.item_data_keys[sesh.current_img_signature]['price']][sesh.item_data_keys[sesh.current_img_signature]['Paletteid']][itemidx_item[1]][itemidx_item[0]]['href'] for itemidx_item in sesh.display_items_[sesh.current_img_signature] if itemidx_item[1] not in ['Palette', 'Living Room', 'Bedroom']]
sesh.responses = asyncio.run(main(urls))
urls = ['https://dreamdemo.pythonanywhere.com/store_shop' for _ in range(len(urls))]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
responses = [r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses]
item_locator_data = [sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']]
json_data = [json.dumps({'response': responses[i], 'item_locator_data': item_locator_data[i]}) for i,url in enumerate(urls)]
responses = asyncio.run(main_post(urls, headers, json_data, timeout=.5))
print('*-/*/-*-roomItemClick: dumped store_shop: ', item_locator_data)
formats = ['Youtube Long-Form', 'Youtube Short-Form', 'Facebook Long-Form', 'Instagram Reel', 'Tiktok', 'LinkedIn']
number_of_items = [7, 3, 7, 3, 3, 7]
urls = [sesh.item_data[sesh.current_img_signature][sesh.item_data_keys[sesh.current_img_signature]['room_type']][sesh.item_data_keys[sesh.current_img_signature]['room_style']][sesh.item_data_keys[sesh.current_img_signature]['price']][sesh.item_data_keys[sesh.current_img_signature]['Paletteid']][itemidx_item[1]][itemidx_item[0]]['href'] for itemidx_item in sesh.display_items_[sesh.current_img_signature] if itemidx_item[1] not in ['Palette', 'Living Room', 'Bedroom']]
sesh.responses = asyncio.run(main(urls))
#urls = ['https://dreamdemo.pythonanywhere.com/scriptgen_promise' for _ in range(len(formats))]
#headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
responses = [[r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses] for _ in range(len(formats))]
item_locator_data = [[sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']] for _ in range(len(formats))]
items = [[data[1] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']] for _ in range(len(formats))]
idxs = [list(range(len(items))) for i,_ in enumerate(formats)]
process = {}
for i,_ in enumerate(formats):
if formats[i] in sesh.frmt_idxs_maps[sesh.current_img_signature] and all([tupe in item_locator_data[0] for tupe in sesh.frmt_idxs_maps[sesh.current_img_signature][formats[i]]]):
process[i] = False
np.random.shuffle(idxs[i])
idxs[i] = idxs[i][:number_of_items[i]]
sesh.frmt_idxs_maps[sesh.current_img_signature][formats[i]] = [item_locator_data[i][idx] for idx in idxs[i]]
sesh.frmt_id_maps[sesh.current_img_signature][formats[i]] = str(time.time())
process[i] = True
time.sleep(.001)
#json_data = [json.dumps({'video_format': fmt, 'number_of_items': number_of_items[i], 'room_type': sesh.room_type, 'item_locator_data': item_locator_data, 'gen_uid': i, 'responses':responses, 'items': items}) for i,fmt in enumerate(formats)]
json_data = [json.dumps({'video_format': fmt, 'number_of_items': number_of_items[i], 'idxs':idxs[i][:number_of_items[i]], 'room_type': sesh.room_type, 'item_locator_data': item_locator_data[i], 'gen_uid': sesh.frmt_id_maps[sesh.current_img_signature][formats[i]], 'seshid':seshid, 'items': items[i]}) for i,fmt in enumerate(formats) if process[i]]
urls = ['https://dreamdemo.pythonanywhere.com/scriptgen_promise' for i in range(len(formats)) if process[i]]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(formats) if process[i]]
print('*-/*/-*-roomItemClick -- processed: ', len(json_data), [(f,process[i], idxs[i]) for i,f in enumerate(formats)])
responses = asyncio.run(main_post(urls, headers, json_data, timeout=.5))
#responses = asyncio.run(main_post(urls, headers, json_data, timeout=3))
print('*-/*/-*-roomItemClick: dumped scriptgen_promise: ', responses)"""
return gr.Column(scale=4), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(1)), gr.Gallery(visible=False), gr.Label('Dream Home: As Quick As A Click. As Simple As Shopping.', label='Sponsors'), gr.update(visible=bool(0)), seshid
elif selection in ['living room', 'bedroom']:
return gr.Column(scale=4), gr.update(visible=bool(0)), gr.update(visible=bool(1)), gr.update(visible=bool(0)), gr.Gallery(visible=False), gr.Label('Dream Home: As Quick As A Click. As Simple As Shopping.', label='Sponsors', visible=True) if sesh.summary_closed else gr.Label('Dream Home: As Quick As A Click. As Simple As Shopping.', label='Sponsors', visible=False), gr.update(visible=bool(0)) if sesh.summary_closed else gr.update(visible=bool(1)), seshid
else:
try:
item = evt.value['caption']
replacements = [(product['img'] if itemi in sesh.inbudget[sesh.current_img_signature][item] else sesh.default_img, product['price']) for itemi,product in enumerate(sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Paletteid][item])]
return gr.Column(scale=4), gr.update(visible=bool(1)), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.Gallery(replacements, 'Item Replacements', height=150, rows=1, columns=7, visible=True, interactive=True), gr.Label(visible=False), gr.update(visible=bool(0)), seshid
except:
return gr.Column(scale=5), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.Gallery([], 'Item Replacements', rows=1, columns=7, visible=False, interactive=True), gr.Label(visible=True), gr.update(visible=bool(0)), seshid
def closeSidePanel(seshid):
sesh = getSesh(seshid)
setSesh(seshid, sesh)
return gr.Column(scale=5), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.Label('No Item Selected', label='Merchant'), gr.Gallery(visible=False), gr.Label('Dream Home: As Quick As A Click. As Simple As Shopping.', label='Sponsors', visible=True), gr.update(visible=bool(0))
def productClick(evt: gr.SelectData, seshid):
sesh = getSesh(seshid)
if not sesh.clicked_displayed_product:
return gr.Label('No Item Selected', label='Merchant')
product_idx = evt.index
sesh.product_idx = evt.index
product = sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Paletteid][sesh.clicked_displayed_product][product_idx]
sesh.product = product
lookup_idxs = sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Paletteid][sesh.clicked_displayed_product][product_idx]
sesh.clicked_product_data = {'item': sesh.clicked_displayed_product, 'lookup_idxs': lookup_idxs}
setSesh(seshid, sesh)
return gr.Label(product['store'].split('-')[0], label='Merchant')
def replaceProduct(seshid):
sesh = getSesh(seshid)
item_idx = sesh.items.index(sesh.clicked_displayed_product)
sesh.updated_display[item_idx] = (sesh.product['img'], sesh.clicked_displayed_product)
#sesh.display_items[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Paletteid][item_idx] = (sesh.product_idx, sesh.clicked_displayed_product) if sesh.product_idx in sesh.inbudget[sesh.current_img_signature][sesh.clicked_displayed_product] else sesh.display_items[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Paletteid][item_idx]
sesh.display_items_[sesh.current_img_signature][item_idx] = (sesh.product_idx, sesh.clicked_displayed_product) if sesh.product_idx in sesh.inbudget[sesh.current_img_signature][sesh.clicked_displayed_product] else sesh.display_items_[sesh.current_img_signature][item_idx]
for item_dataidx in sesh.display_items_[sesh.current_img_signature]:
if item_dataidx[0] != -1:
store = sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][item_dataidx[1]][item_dataidx[0]]['store']
writeForStoreProcessing(store, sesh.zipcode)
#sesh.summary[sesh.current_img_signature] = [() if itemidx_item[1] in ['Palette', 'Living Room', 'Bedroom'] else (itemidx_item[1], sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Paletteid][itemidx_item[1]][itemidx_item[0]]) for itemidx_item in sesh.display_items[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Paletteid]]
sesh.summary[sesh.current_img_signature] = [() if itemidx_item[1] in ['Palette', 'Living Room', 'Bedroom'] else (itemidx_item[1], sesh.item_data[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Paletteid][itemidx_item[1]][itemidx_item[0]]) for itemidx_item in sesh.display_items_[sesh.current_img_signature]]
summarisePerStore(seshid)
#print('replaceProduct: ', sesh.product_idx, sesh.clicked_displayed_product, sesh.product_idx in sesh.inbudget[sesh.current_img_signature][sesh.clicked_displayed_product], sesh.display_items_, sum([float(item_product[1]['price'].replace('$', '').replace(',', '')) for img in sesh.summary for item_product in sesh.summary[img] if item_product]))
"""if True:
urls = [sesh.item_data[sesh.current_img_signature][sesh.item_data_keys[sesh.current_img_signature]['room_type']][sesh.item_data_keys[sesh.current_img_signature]['room_style']][sesh.item_data_keys[sesh.current_img_signature]['price']][sesh.item_data_keys[sesh.current_img_signature]['Paletteid']][itemidx_item[1]][itemidx_item[0]]['href'] for itemidx_item in sesh.display_items_[sesh.current_img_signature] if itemidx_item[1] not in ['Palette', 'Living Room', 'Bedroom']]
sesh.responses = asyncio.run(main(urls))
urls = ['https://dreamdemo.pythonanywhere.com/store_shop' for _ in range(len(urls))]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
responses = [r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses]
item_locator_data = [sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']]
json_data = [json.dumps({'response': responses[i], 'item_locator_data': item_locator_data[i]}) for i,url in enumerate(urls)]
responses = asyncio.run(main_post(urls, headers, json_data, timeout=.5))
print('*-/*/-*-replaceProduct: dumped store_shop: ', item_locator_data)
formats = ['Youtube Long-Form', 'Youtube Short-Form', 'Facebook Long-Form', 'Instagram Reel', 'Tiktok', 'LinkedIn']
number_of_items = [7, 3, 7, 3, 3, 7]
urls = [sesh.item_data[sesh.current_img_signature][sesh.item_data_keys[sesh.current_img_signature]['room_type']][sesh.item_data_keys[sesh.current_img_signature]['room_style']][sesh.item_data_keys[sesh.current_img_signature]['price']][sesh.item_data_keys[sesh.current_img_signature]['Paletteid']][itemidx_item[1]][itemidx_item[0]]['href'] for itemidx_item in sesh.display_items_[sesh.current_img_signature] if itemidx_item[1] not in ['Palette', 'Living Room', 'Bedroom']]
sesh.responses = asyncio.run(main(urls))
#urls = ['https://dreamdemo.pythonanywhere.com/scriptgen_promise' for _ in range(len(formats))]
#headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
responses = [[r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses] for _ in range(len(formats))]
item_locator_data = [[sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']] for _ in range(len(formats))]
items = [[data[1] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']] for _ in range(len(formats))]
idxs = [list(range(len(items))) for i,_ in enumerate(formats)]
process = {}
for i,_ in enumerate(formats):
print('*-/*/-*-replaceProduct -- prep: ', formats[i], formats[i] in sesh.frmt_idxs_maps[sesh.current_img_signature], all([tupe in item_locator_data[0] for tupe in sesh.frmt_idxs_maps[sesh.current_img_signature][formats[i]]]), sesh.frmt_idxs_maps[sesh.current_img_signature][formats[i]] if formats[i] in sesh.frmt_idxs_maps[sesh.current_img_signature] else None, '*****', item_locator_data[0])
if formats[i] in sesh.frmt_idxs_maps[sesh.current_img_signature] and all([tupe in item_locator_data[0] for tupe in sesh.frmt_idxs_maps[sesh.current_img_signature][formats[i]]]):
process[i] = False
continue
np.random.shuffle(idxs[i])
idxs[i] = idxs[i][:number_of_items[i]]
sesh.frmt_idxs_maps[sesh.current_img_signature][formats[i]] = [item_locator_data[i][idx] for idx in idxs[i]]
sesh.frmt_id_maps[sesh.current_img_signature][formats[i]] = str(time.time())
process[i] = True
time.sleep(.001)
json_data = [json.dumps({'video_format': fmt, 'number_of_items': number_of_items[i], 'idxs':idxs[i][:number_of_items[i]], 'room_type': sesh.room_type, 'item_locator_data': item_locator_data[i], 'gen_uid': sesh.frmt_id_maps[sesh.current_img_signature][formats[i]], 'seshid':seshid, 'items': items[i]}) for i,fmt in enumerate(formats) if process[i]]
urls = ['https://dreamdemo.pythonanywhere.com/scriptgen_promise' for i in range(len(formats)) if process[i]]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(formats) if process[i]]
print('*-/*/-*-replaceProduct -- processed: ', len(json_data), [(f,process[i], idxs[i]) for i,f in enumerate(formats)])
if json_data:
responses = asyncio.run(main_post(urls, headers, json_data, timeout=.5))
#responses = asyncio.run(main_post(urls, headers, json_data, timeout=3))
else:
responses = []
print('*-/*/-*-replaceProduct: dumped scriptgen_promise: ', responses)"""
setSesh(seshid, sesh)
return gr.Column(scale=5), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.Label('No Item Selected', label='Merchant'), gr.Gallery(visible=False), gr.Label('Dream Home: As Quick As A Click. As Simple As Shopping.', label='Sponsors', visible=True), gr.Gallery(sesh.updated_display, label='Room Items', columns=5)
def selectMerchantItemCountAndTotal(store, seshid):
sesh = getSesh(seshid)
num_items = 0
total = 0
for item in sesh.summary_joined[store]:
for description in sesh.summary_joined[store][item]:
price = sesh.summary_joined[store][item][description]['product_dict']['price']
count = sesh.summary_joined[store][item][description]['count']
total += float(price.replace('$', '').replace(',', '')) * count
num_items += count
setSesh(seshid, sesh)
return num_items, total
def selectMerchantItemCountAndTotal(store, seshid):
sesh = getSesh(seshid)
num_items = 0
total = 0
for item in sesh.summary_joined[store]:
price = sesh.summary_joined[store][item]['product_dict']['price']
count = sesh.summary_joined[store][item]['count']
total += float(price.replace('$', '').replace(',', '')) * count
num_items += count
setSesh(seshid, sesh)
return num_items, total
from huggingface_hub import InferenceClient
def retrieveProcessedStoreData(store, seshid):
sesh = getSesh(seshid)
"""if os.path.isfile(f'C:\\Users\\Wayne\\Documents\\store_processors\\completed_{store+sesh.zipcode}.json'):
with open(f'C:\\Users\\Wayne\\Documents\\store_processors\\completed_{store+sesh.zipcode}.json', 'r') as file:
data = json.load(file)
return data['store_data']
else:
return []"""
return []
setSesh(seshid, sesh)
def summaryClick(seshid):
sesh = getSesh(seshid)
#from pathlib import Path
sesh.counts_totals = {store:selectMerchantItemCountAndTotal(store, seshid) for store in sesh.summary_joined}
all_counts = str(sum([ct[0] for store,ct in sesh.counts_totals.items()]))
all_totals = sum([ct[1] for store,ct in sesh.counts_totals.items()])
print('summaryClick -- counts_totals: ', all_counts, all_totals, sesh.counts_totals)
if sesh.summary_closed:
sesh.summary_closed = False
store_data = {store: (lambda data: '' if not data or store.split()[0].lower() not in data[0]['STORE'].lower() or 'ZIPCODE' not in data[0] or 'PHONE' not in data[0] or 'STATE' not in data[0] or data[0]['STATE'] != sesh.state or len(data[0]['STATE']) != 2 or len(data[0]['PHONE']) != 12 else '\n'.join(['\n'.join([('\t\t\t'+key if key.lower() != 'store' else '\t\tNAME')+': '+value for key,value in d.items()]) for d in data]))(retrieveProcessedStoreData(store, seshid)) for store in sesh.summary_joined}
#store_data = {store: (lambda data: '' if not data or 'zipcode' not in data[0] else '\n'.join([str(d) for d in data]))(retrieveProcessedStoreData(store, seshid)) for store in sesh.summary_joined}
item_summary_data = '\n\n'.join(['STORE: '+store+'\n'+('\tLOCATIONS: N/A' if not store_data[store] else '\tLOCATIONS: \n'+store_data[store])+''.join(['\n\tPRODUCT: '+ product +'\n\tPRICE: '+pd_count['product_dict']['price']+'\n\tSOURCE: '+pd_count['product_dict']['href'] for product,pd_count in sesh.summary_joined[store].items()]) for store in sesh.summary_joined])
print('store summary: ', {store: retrieveProcessedStoreData(store, seshid) for store in sesh.summary_joined})
setSesh(seshid, sesh)
return gr.Button('Suppress Summary'), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(1)), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(1)), gr.Dropdown(list(sesh.summary_joined), label='Merchants', interactive=True), gr.Label('All', label='Merchant'), gr.Label(all_counts, label='Number of Items'), gr.Label('$'+str(np.round(all_totals, 2)), label='Total'), item_summary_data
#'\n\n'.join(['Store: '+store+'\n\n'+'\n\n'.join(['\n\tProduct: '+ product +'\n\tPrice: '+pd_count['product_dict']['price']+'\n\tSource: '+pd_count['product_dict']['href'] for product,pd_count in sesh.summary_joined[store].items()]) for store in sesh.summary_joined])
else:
sesh.summary_closed = True
setSesh(seshid, sesh)
return gr.Button('Summarise'), gr.update(visible=bool(1)), gr.update(visible=bool(1)), gr.update(visible=bool(1)), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(1)), gr.update(visible=bool(0)), gr.Dropdown(), gr.Label(), gr.Label(), gr.Label(), ''
def selectMerchantProduct(evt: gr.SelectData, seshid):
sesh = getSesh(seshid)
store = evt.value
sesh.summary_store = store
#print('selectMerchantProduct -- counts_totals: ', counts_totals)
setSesh(seshid, sesh)
return gr.Dropdown(list(sesh.summary_joined[store]), label='Items', interactive=True), gr.Label(sesh.summary_store if sesh.summary_store else 'All', label='Merchant'), gr.Label(str(sesh.counts_totals[store][0]), label='Number of Items'), gr.Label('$'+str(np.round(sesh.counts_totals[store][1], 2)), label='Total')
def getVizText(html):
from bs4 import BeautifulSoup, NavigableString, Tag
soup = BeautifulSoup(str(html), 'html.parser')
viz_text = [tag.text for tag in soup.find_all() if tag.text and len(tag.find_all())==0 and tag.name not in ['style', 'script', 'head', 'title', 'meta', '[document]'] and not isinstance(tag, NavigableString)]
viz_text_str = '...'.join(viz_text).replace('\\n', '').replace('\\t', '').replace('\n', '').replace('\t', '')
return viz_text_str
def findShoppingRelevantTerms(html):
if not html:
return {}
if True: #try:
start = time.time()
print('findShoppingRelevantTerms: getting viztext')
viz_text_str = getVizText(str(html.decode("utf-8")))
print('findShoppingRelevantTerms -- got viztext: ', time.time()-start)
search_terms = [' off ', ' availability ', ' available ', ' delivery ', ' deliver ', ' ship ', ' shipping ', ' return ', ' returns ', ' exchange ', ' exchanges ', ' material ', ' materials ']
print('findShoppingRelevantTerms: getting found_terms')
start = time.time()
#found_terms = {t:(lambda text, term_loc: text[term_loc-200:term_loc+300])(viz_text_str, viz_text_str.lower().find(t.lower())) for t in search_terms if t in viz_text_str}
found_terms = {t:(lambda text, term_loc: text[term_loc-500:term_loc+500])(viz_text_str, viz_text_str.lower().find(t.lower())) for t in search_terms if (lambda text, term_loc: (t != ' off ' and t in text[term_loc-500:term_loc+500]) or (t == ' off ' and (t in text[term_loc-500:term_loc+500] or ' off...' in text[term_loc-500:term_loc+500]) and ('%' in text[term_loc-500:term_loc+500] or '$' in text[term_loc-500:term_loc+500])))(viz_text_str, viz_text_str.lower().find(t.lower()))}
print('findShoppingRelevantTerms -- got found_terms: ', time.time()-start)
return found_terms
else: #except:
return {}
def changeSummaryFilter(evt: gr.SelectData, seshid):
sesh = getSesh(seshid)
summary_radio = evt.value
print('changeSummaryFilter: ', summary_radio)
sesh.summary_radio = summary_radio
all_counts = str(sum([ct[0] for store,ct in sesh.counts_totals.items()]))
all_totals = sum([ct[1] for store,ct in sesh.counts_totals.items()])
#if summary_radio == 'Complete' or not hasattr(sesh, 'summary_store'):
if summary_radio == 'Complete':
print('changeSummaryFilter: in Complete')
setSesh(seshid, sesh)
return gr.Label('All', label='Merchant'), gr.Label(all_counts, label='Number of Items'), gr.Label('$'+str(np.round(all_totals, 2)), label='Total'), gr.update(visible=bool(0)), gr.update(visible=bool(1)), gr.update(visible=bool(1)), gr.update(visible=bool(0))
elif summary_radio == 'Script':
uploadStoreShop(seshid)
#textgen for general audience, things to look out for or be aware of
"""product_pd_counts = [(product,pd_count) for store in sesh.summary_joined for product,pd_count in sesh.summary_joined[store].items()]
urls = [product_pd_count[1]['product_dict']['href'] for product_pd_count in product_pd_counts]
start = time.time()
responses = asyncio.run(main(urls))
end = time.time()
lapse = end-start
#fdsdweesdd = findShoppingRelevantTerms(responses[0])
#print('changeSummaryFilter -- in Script: ', lapse, fdsdweesdd)
start = time.time()
found_terms_4_room_items = [(product_pd_counts[ir][0], findShoppingRelevantTerms(r)) for ir,r in enumerate(responses)]
url = 'https://dreamdemo.pythonanywhere.com/shopping'
valid_data = {'product_pd_counts': product_pd_counts, 'responses':responses}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(valid_data), headers=headers)
jsondata = json.loads(r.content)
print('changeSummaryFilter: ', jsondata)
del responses
#dsdsd = 'ITEM TOPICS: \n\n'+'\n\n'.join(['ITEM : '+data[0].upper() + f'\n\n{data[0].upper()} TOPICS: \n'+'\n\n'.join(['Topic: '+term[1:-1].upper()+'\n...'+text for term,text in data[1].items()]) for idx,data in enumerate(found_terms_4_room_items ) if data[1]])
start = time.time()
topics = 'ITEM TOPICS: \n\n'+'\n\n'.join(['\n\n'.join([f'{data[0].upper()} TOPIC: '+term[1:-1].upper()+'\n...'+text for term,text in data[1].items()]) for idx,data in enumerate(found_terms_4_room_items ) if data[1]])
descriptions = '\n\n'+'\n\n'.join(['Store: '+store+'\n\n'.join(['\n\tProduct: '+ product.upper() +'\n\tDescription: '+pd_count['product_dict']['description']+'\n\tPrice: '+pd_count['product_dict']['price'] for product,pd_count in sesh.summary_joined[store].items()]) for store in sesh.summary_joined])
prompt = topics + "\n\nITEMS: \n\n"+descriptions+"\n\nTask: Referencing the ITEMS provided, create an audio script about shopping to decorate a room, writing to prompt the listener for their feedback as to whether the items chosen are choices they might have made; where applicable, incorporate the corresponding ITEM TOPICS to the ITEM being written about, and do so in a way that is informing the listener of what they might expect during the ordering process -- reference the ITEM TOPICS in a fun way as if you are engaging in small talk, making remarks to the respective ITEM TOPICS in a 'just a heads up' tangent and then getting back on script. Write in the past tense, like we have already decorated and are now reviewing the items chosen to outfit the room, speculating as to the listener's stance on the items chosen, whether they would like the ITEM being spoken about and why (be creative, thinking of random reasons the listener would or would not like the ITEM chosen). Write in an informal style. Keep in mind, the items have NOT been ordered and shipped yet."
items_prepped = ['\n\n'.join([f'ITEM: {data[0].upper()}\n\n'+f'{data[0].upper()} STORE: '+product_pd_counts[idx][1]['product_dict']['store']+'\n\n'+f'{data[0].upper()} DESCRIPTION: '+product_pd_counts[idx][1]['product_dict']['description']+'\n\n'+'\n\n'.join([f'{data[0].upper()} TOPIC: '+(term[1:-1].upper() if term[1:-1] != 'ship' else 'SHIPPING')+'\n...'+text for term,text in data[1].items()])]) for idx,data in enumerate(found_terms_4_room_items)]
#print('indivij prep: ', items_prepped , len(items_prepped))
templates = {0:['For ITEM, we went with the ITEM DESCRIPTION. SPECULATED RESPONSE.', 'SPECULATED RESPONSE, so for ITEM we went with the ITEM DESCRIPTION.'], 1:['For ITEM, we went with the ITEM DESCRIPTION. ITEM TOPIC. SPECULATED RESPONSE.', 'SPECULATED RESPONSE, so for ITEM we went with the ITEM DESCRIPTION. ITEM TOPIC.'], 2:['For ITEM, we went with the ITEM DESCRIPTION. ITEM TOPICS. SPECULATED RESPONSE.', 'SPECULATED RESPONSE, so for ITEM we went with the ITEM DESCRIPTION. ITEM TOPICS.']}
responses = []"""
#for idx,data in enumerate(found_terms_4_room_items):
#template = templates[len(data[1]) if len(data[1])<2 else 2][np.random.choice([0,1])]
#prompt = items_prepped[idx]+'\n\nTEMPLATE: '+template+"\n\nTASK: adapt TEMPLATE using the ITEM/DESCRIPTION/STORE info provided, where SPECULATED RESPONSE is your creative guess as to the reader's stance on the items chosen, whether they would like the ITEM being written about and why (be creative, thinking of random reasons the reader would or would not like the ITEM chosen). Write from the perspective of reporting to someone who is considering purchasing a home and you are presenting different decorative options that might persuade them to buy the home; so, make sure your wording reflects this -- 'if you go with...', 'now keep in mind...', 'were you to purchase this home...' and the like are examples of how you might word things. You don't have to use these examples exactly, just word things similarly. Be creative."
#if data[1]:
#prompt += " Incorporate each ITEM TOPIC in a way that is a heads up for the reader to inform them of the purchase process and what they can expect. Reference the each ITEM TOPIC in a fun way as if you are engaging in small talk, making remarks to the respective ITEM TOPIC info in a 'just a heads up' tangent and then getting back on script."
#prompt += f" This should read as a review of an item chosen for a room being furnished, but the item has NOT been purchased or shipped yet. Write in an informal style. And to clarify, you are writing AS a reviewer, FOR a prospective home buyer, ABOUT an item FROM a store, and the likely buying experience with them (the store); you are writing about decorating a {sesh.room_type}. "
#if idx==0:
#prompt += "Keep in mind this is the first of many items we are reviewing, so ensure your writing reflects the fact that this is just the first item being reported on."
#elif idx==len(found_terms_4_room_items)-1:
#prompt += "Keep in mind this is the last of many items we are reviewing, so ensure your writing reflects the fact that this is the final item being reported on and do a review wrap-up/send off for this particular room's decor review. Maybe begin by writing something along the lines of 'Okay lastly we have the...' or 'Well, our final item is...' or what have you jare examples of how you might word things. You don't have to use these examples exactly, just word things similarly. Be creative.."
#else:
#prompt += "Keep in mind this is one of many items we have already reviewed and one of other yet to be reviewed, so ensure your writing reflects the fact that this is just the next item being reported on. Maybe begin by writing something along the lines of 'Okay now we have...' or 'So next up is...' or what have you are examples of how you might word things. You don't have to use these examples exactly, just word things similarly. Be creative."
#response = client.text_generation(prompt, model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
#response = response.replace("I know what you're thinking", np.random.choice(alarm3)).replace("I know what you are thinking", np.random.choice(alarm3))
#print('script response: ', response)
#responses.append(response)
#time.sleep(.7)
#response = client.text_generation('\n\n'.join(responses)+"\n\nTASK: summarize this script for a tiktok video about a prospective homebuyer decorating this {sesh.room_type} should they purchase the home. The review should cover the following topics: { ', '.join([data[0] for idx,data in enumerate(found_terms_4_room_items)])}", model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
#print('\n\ntiktok response: ', response)
#response = client.text_generation('\n\n'.join(responses)+"\n\nTASK: summarize this script for a youtube short about a prospective homebuyer decorating this {sesh.room_type} should they purchase the home. The review should cover the following topics: {', '.join([data[0] for idx,data in enumerate(found_terms_4_room_items)])}", model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
#print('\n\nyoutube short response: ', response) #script response:
#preprompt = 'ITEMS: \n\n'+'\n\n'.join(['\n\n'.join([f'ITEM: {data[0].upper()}\n\n'+f'{data[0].upper()} STORE: '+product_pd_counts[idx][1]['product_dict']['store']+'\n\n'+f'{data[0].upper()} DESCRIPTION: '+product_pd_counts[idx][1]['product_dict']['description']+'\n\n'+'\n\n'.join([f'{data[0].upper()} TOPIC: '+term[1:-1].upper()+'\n...'+text for term,text in data[1].items()])]) for idx,data in enumerate(found_terms_4_room_items)])
#prompt = preprompt+"\n\nTask: Referencing the ITEMS provided -- each item DESCRIPTION, in particular -- create an audio script about shopping to decorate a room, writing to prompt the listener for their feedback as to whether the items chosen are choices they might have made; where applicable, incorporate the corresponding ITEM TOPICS to the item DESCRIPTION being written about, and do so in a way that is informing the listener of what they might expect during the ordering process. Reference the ITEM TOPICS in a fun way as if you are engaging in small talk, making remarks to the respective ITEM TOPIC in a 'just a heads up' tangent and then getting back on script. Write in the past tense, like we have already decorated and are now reviewing the items chosen to outfit the room, speculating as to the listener's stance on the items chosen, whether they would like the ITEM being spoken about and why (be creative, thinking of random reasons the listener would or would not like the ITEM chosen). Write in an informal style."
#end = time.time()
setSesh(seshid, sesh)
return gr.Label('All', label='Merchant'), gr.Label(all_counts, label='Number of Items'), gr.Label('$'+str(np.round(all_totals, 2)), label='Total'), gr.update(visible=bool(0)), gr.update(visible=bool(1)), gr.update(visible=bool(1)), gr.update(visible=bool(0))
else:
setSesh(seshid, sesh)
return gr.Label(sesh.summary_store if hasattr(sesh, 'summary_store') and sesh.summary_store else 'All', label='Merchant'), gr.Label(str(sesh.counts_totals[sesh.summary_store][0]) if hasattr(sesh, 'summary_store') and sesh.summary_store else '--', label='Number of Items'), gr.Label('$'+str(np.round(sesh.counts_totals[sesh.summary_store][1], 2)) if hasattr(sesh, 'summary_store') and sesh.summary_store else '--', label='Total'), gr.update(visible=bool(1)), gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(1))
def displaySource(evt: gr.SelectData, seshid):
sesh = getSesh(seshid)
product = evt.value
sesh.summary_product = product
#sources = '\n\n'.join(['Price: '+pd_count['product_dict']['price']+'\n\nSource: '+pd_count['product_dict']['href'] for description_key,pd_count in sesh.summary_joined[sesh.summary_store][product].items()])
sources = 'Price: '+sesh.summary_joined[sesh.summary_store][product]['product_dict']['price']+'\n\nSource: '+sesh.summary_joined[sesh.summary_store][product]['product_dict']['href']
setSesh(seshid, sesh)
return gr.Markdown(sources), gr.Number(value=sesh.summary_joined[sesh.summary_store][product]['count'], label='Item Count', minimum=0)
def updateProductCount(count, seshid):
sesh = getSesh(seshid)
sesh.summary_joined[sesh.summary_store][sesh.summary_product]['count'] = count
sesh.counts_totals = {store:selectMerchantItemCountAndTotal(store) for store in sesh.summary_joined}
all_counts = str(sum([ct[0] for store,ct in sesh.counts_totals.items()]))
all_totals = sum([ct[1] for store,ct in sesh.counts_totals.items()])
setSesh(seshid, sesh)
return gr.Label(str(sesh.counts_totals[sesh.summary_store][0]) if sesh.summary_store and sesh.summary_radio != 'Complete' else all_counts, label='Number of Items'), gr.Label('$'+str(np.round(sesh.counts_totals[sesh.summary_store][1], 2)) if sesh.summary_store and sesh.summary_radio != 'Complete' else '$'+str(np.round(all_totals, 2)), label='Total')
def updateBudget(budget_number, seshid):
sesh = getSesh(seshid)
sesh.budget_number = float(budget_number)
#sesh.item_budgets = {img: {item: int(weight*sesh.budget_number) for item,weight in weights.items()} for img,weights in sesh.product_means_weights.items()}
#print('updateBudget: ', sesh.budget_number, sesh.item_budgets)
display = updateItemDisplay(seshid, budget=True)
sesh.counts_totals = {store:selectMerchantItemCountAndTotal(store, seshid) for store in sesh.summary_joined}
all_counts = str(sum([ct[0] for store,ct in sesh.counts_totals.items()]))
all_totals = sum([ct[1] for store,ct in sesh.counts_totals.items()])
setSesh(seshid, sesh)
return display, gr.Label(all_counts, label='Number of Items'), gr.Label('$'+str(np.round(all_totals, 2)), label='Total')
def showPalettes(seshid):
return gr.update(visible=bool(1)), gr.update(visible=bool(0)), gr.update(visible=bool(0))
def showScripts(seshid):
return gr.update(visible=bool(0)), gr.update(visible=bool(1)), gr.update(visible=bool(0)), 'load'
def showJourneys(seshid):
return gr.update(visible=bool(0)), gr.update(visible=bool(0)), gr.update(visible=bool(1))
templates = {0:['For ITEM, we went with the ITEM DESCRIPTION. SPECULATED RESPONSE.', 'SPECULATED RESPONSE, so for ITEM we went with the ITEM DESCRIPTION.'], 1:['For ITEM, we went with the ITEM DESCRIPTION. ITEM TOPIC. SPECULATED RESPONSE.', 'SPECULATED RESPONSE, so for ITEM we went with the ITEM DESCRIPTION. ITEM TOPIC.'], 2:['For ITEM, we went with the ITEM DESCRIPTION. ITEM TOPICS. SPECULATED RESPONSE.', 'SPECULATED RESPONSE, so for ITEM we went with the ITEM DESCRIPTION. ITEM TOPICS.']}
def makeItemPrompt(idx,data, seshid):
sesh = getSesh(seshid)
template = templates[len(data[1]) if len(data[1])<2 else 2][np.random.choice([0,1])]
prompt = sesh.items_prepped[idx]+'\n\nTEMPLATE: '+template+"\n\nTASK: adapt TEMPLATE using the ITEM/DESCRIPTION/STORE info provided, where SPECULATED RESPONSE is your creative guess as to the reader's stance on the items chosen, whether they would like the ITEM being written about and why (be creative, thinking of random reasons the reader would or would not like the ITEM chosen). Write from the perspective of reporting to someone who is considering purchasing a home and you are presenting different decorative options that might persuade them to buy the home; so, make sure your wording reflects this -- 'if you go with...', 'now keep in mind...', 'were you to purchase this home...' and the like are examples of how you might word things. You don't have to use these examples exactly, just word things similarly. Be creative."
if data[1]:
prompt += " Incorporate each ITEM TOPIC in a way that is a heads up for the reader to inform them of the purchase process and what they can expect. Reference the each ITEM TOPIC in a fun way as if you are engaging in small talk, making remarks to the respective ITEM TOPIC info in a 'just a heads up' tangent and then getting back on script."
prompt += f" This should read as a review of an item chosen for a room being furnished, but the item has NOT been purchased or shipped yet. Write in an informal style. And to clarify, you are writing AS a reviewer, FOR a prospective home buyer, ABOUT an item FROM a store, and the likely buying experience with them (the store); you are writing about decorating a {sesh.room_type}. "
if idx==0:
prompt += "Keep in mind this is the first of many items we are reviewing, so ensure your writing reflects the fact that this is just the first item being reported on, including a proper intro to get started."
elif idx==len(sesh.found_terms_4_room_items)-1:
prompt += "Keep in mind this is the last of many items we are reviewing, so ensure your writing reflects the fact that this is the final item being reported on and do a review wrap-up/send off for this particular room's decor review. Maybe begin by writing something along the lines of 'Okay lastly we have the...' or 'Well, our final item is...' or what have you are examples of how you might word things. You don't have to use these examples exactly, just word things similarly. Be creative."
else:
prompt += "Keep in mind this is the one of many items we have already reviewed and one of other yet to be reviewed, so ensure your writing reflects the fact that this is just the next item being reported on. Maybe begin by writing something along the lines of 'Okay now we have...' or 'So next up is...' or what have you are examples of how you might word things. You don't have to use these examples exactly, just word things similarly. Be creative."
setSesh(seshid, sesh)
return prompt
def generateScriptForItem(idx,data, seshid):
sesh = getSesh(seshid)
prompt = makeItemPrompt(idx,data)
#tg_response = client.text_generation(prompt, model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
tg_response = getTextGen(prompt)
tg_response = tg_response.replace("I know what you're thinking", np.random.choice(alarm3)).replace("I know what you're thinking", np.random.choice(alarm3))
sesh.tg_responses.append(tg_response)
setSesh(seshid, sesh)
def generateScriptForItem(seshid):
sesh = getSesh(seshid)
url = 'https://dreamdemo.pythonanywhere.com/script_gen'
valid_data = {'room_type': sesh.room_type, 'idx': sesh.found_terms_4_room_items_idx, 'gen_uid': sesh.gen_uid}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(valid_data), headers=headers)
jsondata = json.loads(r.content)
tg_response = jsondata['response']
print('generateScriptForItem from endpoint: ', tg_response)
sesh.tg_responses.append(tg_response)
setSesh(seshid, sesh)
def loadColorAndCharacter(text, seshid):
sesh = getSesh(seshid)
if text == 'load':
sesh.product_pd_counts = [(product,pd_count) for store in sesh.summary_joined for product,pd_count in sesh.summary_joined[store].items()]
sesh.tg_responses = []
urls = [product_pd_count[1]['product_dict']['href'] for product_pd_count in sesh.product_pd_counts]
"""sesh.responses = asyncio.run(main(urls))
#gen_uid = str(time.time())
item_locator_data = {data[1]: sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']}
print('item_locator_data: ', item_locator_data, '\n/*/*', [item_locator_data[product_pd_count[0]] for i,product_pd_count in enumerate(sesh.product_pd_counts)])
responses = [r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses]
urls = ['https://dreamdemo.pythonanywhere.com/dump_text_gen' for _ in range(len(sesh.product_pd_counts))]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
for item,idxs in item_locator_data.items():
if tuple(idxs) not in sesh.locator_genid: sesh.locator_genid[tuple(idxs)] = gen_uid = str(time.time())
json_data = [json.dumps({'room_type': sesh.room_type, 'item_locator_data': item_locator_data[product_pd_count[0]], 'gen_uid': sesh.locator_genid[tuple(item_locator_data[product_pd_count[0]])], 'response':responses[i], 'item': product_pd_count[0]}) for i,product_pd_count in enumerate(sesh.product_pd_counts) if product_pd_count[0] not in ['Palette', 'Living Room', 'Bedroom']]
responses = asyncio.run(main_post(urls, headers, json_data, timeout=3))
print('dump_text_gen: ', responses)"""
"""dummy = dummy_
print('sesh.display_items_[sesh.current_img_signature]: ', sesh.display_items_[sesh.current_img_signature])
print('item_data_: ', [(k,len(v)) for k,v in sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]].items() if k not in ['Palette', 'Living Room', 'Bedroom']])
item_locator_data = {data[1]: sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]] for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']}
print('item_locator_data: ', item_locator_data)
url = 'https://dreamdemo.pythonanywhere.com/shopping'
sesh.gen_uid = str(time.time())
valid_data = {'gen_uid': sesh.gen_uid, 'item_locator_data': item_locator_data, 'product_pd_counts': sesh.product_pd_counts, 'responses':[r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses]}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(valid_data), headers=headers)
jsondata = json.loads(r.content)"""
"""urls = ['https://dreamdemo.pythonanywhere.com/script_gen' for _ in range(len(sesh.product_pd_counts))]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
json_data = [json.dumps({'room_type': sesh.room_type, 'idx': i, 'gen_uid': sesh.gen_uid}) for i in range(len(sesh.product_pd_counts))]
responses = asyncio.run(main_post(urls, headers, json_data))"""
#sesh.found_terms_4_room_items = jsondata['response']
"""print('loadColorAndCharacter: ', jsondata['response'])
urls = ['https://dreamdemo.pythonanywhere.com/script_gen' for _ in range(1)]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
json_data = [json.dumps({'room_type': sesh.room_type, 'idx': i, 'gen_uid': sesh.gen_uid, 'model': i}) for i in range(1)]
try:
responses = asyncio.run(main_post(urls, headers, json_data, timeout=7))
except:
pass
urls = ['https://dreamdemo.pythonanywhere.com/script_gen' for _ in range(4)]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
json_data = [json.dumps({'room_type': sesh.room_type, 'idx': i, 'gen_uid': sesh.gen_uid, 'model': i}) for i in range(4)]
try:
responses = asyncio.run(main_post(urls, headers, json_data, timeout=1))
except:
pass
setSesh(seshid, sesh)"""
return 'loaded'
else:
setSesh(seshid, sesh)
return 'not loaded'
def searchColorAndCharacter(text, seshid):
sesh = getSesh(seshid)
if text == 'search':
"""url = 'https://dreamdemo.pythonanywhere.com/shopping'
sesh.gen_uid = str(time.time())
valid_data = {'gen_uid': sesh.gen_uid, 'product_pd_counts': sesh.product_pd_counts, 'responses':[r.decode('ISO-8859-1') if type(r) != type(None) else r for r in sesh.responses]}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(valid_data), headers=headers)
jsondata = json.loads(r.content)
#sesh.found_terms_4_room_items = jsondata['response']
print('searchColorAndCharacter: ', jsondata['response'])
urls = ['https://dreamdemo.pythonanywhere.com/script_gen' for _ in range(1)]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
json_data = [json.dumps({'room_type': sesh.room_type, 'idx': i, 'gen_uid': sesh.gen_uid, 'model': i}) for i in range(1)]
try:
responses = asyncio.run(main_post(urls, headers, json_data, timeout=7))
except:
pass
urls = ['https://dreamdemo.pythonanywhere.com/script_gen' for _ in range(4)]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
json_data = [json.dumps({'room_type': sesh.room_type, 'idx': i, 'gen_uid': sesh.gen_uid, 'model': i}) for i in range(4)]
try:
responses = asyncio.run(main_post(urls, headers, json_data, timeout=1))
except:
pass"""
"""start = time.time()
urls = ['https://dreamdemo.pythonanywhere.com/script_gen' for _ in range(len(sesh.product_pd_counts))]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
json_data = [json.dumps({'room_type': sesh.room_type, 'idx': i, 'gen_uid': sesh.gen_uid}) for i in range(len(sesh.product_pd_counts))]
#responses = asyncio.run(main_post(urls, headers, json_data, timeout=180))
end = time.time()
r_ = [r[:250] if r else str(i)+'--N/A' for i,r in enumerate(responses)]
#sesh.tg_responses = [json.loads(r)['response'] if type(r) == type(b'') else '********' for r in responses]
#sesh.tg_responses.append(tg_response)
print('searchColorAndCharacter script_gen: ', (end-start)/60, [(r[:250], sesh.product_pd_counts[i][0]) for i,r in enumerate(sesh.tg_responses)])
"""
"""script_prompts = {'Youtube Long-Form': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a long-form Youtube video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'Youtube Short-Form': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a Youtube Short. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'Facebook Long-Form': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a long-form Facebook video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'Instagram Reel': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for an Instagram Reel video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'Tiktok': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a Tiktok video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'LinkedIn': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a LinkedIn long-form video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.'}
start = time.time()
script_types = [s for s in script_prompts]
urls = ['https://dreamdemo.pythonanywhere.com/textgen' for _ in range(len(script_types))]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
json_data = [json.dumps({'prompts': script_prompts[k]}) for k in script_types]
responses = asyncio.run(main_post(urls, headers, json_data, timeout=180))
end = time.time()
print('searchColorAndCharacter script types: ', end-start, [(r[:250], script_types[i]) for i,r in enumerate(responses)])
"""
#sesh.found_terms_4_room_items = [(sesh.product_pd_counts[ir][0], findShoppingRelevantTerms(r)) for ir,r in enumerate(sesh.responses)]
#print('searchColorAndCharacter 2: ', sesh.found_terms_4_room_items)
#sesh.found_terms_4_room_items_idx = 0
#sesh.scripts = {}
#sesh.items_prepped = ['\n\n'.join([f'ITEM: {data[0].upper()}\n\n'+f'{data[0].upper()} STORE: '+sesh.product_pd_counts[idx][1]['product_dict']['store']+'\n\n'+f'{data[0].upper()} DESCRIPTION: '+sesh.product_pd_counts[idx][1]['product_dict']['description']+'\n\n'+'\n\n'.join([f'{data[0].upper()} TOPIC: '+(term[1:-1].upper() if term[1:-1] != 'ship' else 'SHIPPING')+'\n...'+text for term,text in data[1].items()])]) for idx,data in enumerate(sesh.found_terms_4_room_items)]
#item_prompts = [makeItemPrompt(idx,idata) for idx,idata in enumerate(sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])]
#item_scripts = multiprocessPrompts(item_prompts)
#print('searchColorAndCharacter: ', item_scripts)
setSesh(seshid, sesh)
return 'searched'
else:
setSesh(seshid, sesh)
return 'not searched'
def updateLinksLoadStatus(text, seshid):
sesh = getSesh(seshid)
setSesh(seshid, sesh)
if text == 'loaded':
print('LOADED color and character for script\nadding color and character to script\nstandby...')
return 'LOADED color and character\nadding color and character to scripts\nstandby...', 'search'
else:
return 'searched color and character for script\npreparing script for item1\nstandby...update this', ''
def updateLinksSearchStatus(text, seshid):
sesh = getSesh(seshid)
setSesh(seshid, sesh)
if text == 'searched':
print('ADDED color and character for script\npreparing script for item1\nstandby...')
#return f'ADDED color and character for script\npreparing script for {sesh.product_pd_counts[0][0]}\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby......', 'prep1'
return f'ADDED color and character for script\npreparing all scripts, standby......', 'prep1'
else:
return 'searched color and character for script\npreparing script for item1\nstandby...update this', ''
def prepAllScripts(text, seshid):
sesh = getSesh(seshid)
if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
script_prompts = {'Youtube Long-Form': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a long-form Youtube video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'Youtube Short-Form': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a Youtube Short. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'Facebook Long-Form': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a long-form Facebook video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'Instagram Reel': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for an Instagram Reel video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'Tiktok': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a Tiktok video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.', 'LinkedIn': 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a LinkedIn long-form video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.'}
start = time.time()
script_types = [s for s in script_prompts]
urls = ['https://dreamdemo.pythonanywhere.com/textgen' for _ in range(len(script_types))]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i,_ in enumerate(urls)]
json_data = [json.dumps({'prompts': script_prompts[k]}) for k in script_types]
responses = asyncio.run(main_post(urls, headers, json_data, timeout=210))
end = time.time()
sesh.scripts = {k:json.loads(responses[i])['response'] if type(responses[i]) == type(b'') else 'Unable to complete this script.' for i,k in enumerate(script_types)}
#print('prepItem1ForScript script types: ', (end-start)/60, [(r[:250], script_types[i]) for i,r in enumerate(responses)])
setSesh(seshid, sesh)
return 'good'
else:
setSesh(seshid, sesh)
return 'bad'
def updateAllItemsStatus(text, seshid):
sesh = getSesh(seshid)
completed = len([s for s in sesh.scripts if s != 'Unable to complete this script.'])
if text == 'good' and completed > 0:
setSesh(seshid, sesh)
return f"Color and character updated, {completed} {'scripts' if completed != 1 else 'script'} completed. ", gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
else:
setSesh(seshid, sesh)
return f'Something went wrong, failed to complete scripts.', gr.Dropdown([], label='Scripts', interactive=True)
def prepItem1ForScript(text, seshid):
sesh = getSesh(seshid)
if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
#generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
generateScriptForItem()
sesh.found_terms_4_room_items_idx += 1
setSesh(seshid, sesh)
return f'prepped{sesh.found_terms_4_room_items_idx}'+'-changed for testing'
else:
setSesh(seshid, sesh)
return f'prep{sesh.found_terms_4_room_items_idx} failed'
def updateItem1Status(text, seshid):
sesh = getSesh(seshid)
if text == f'prepped{sesh.found_terms_4_room_items_idx}':
#print('prepItem1forScript: ', sesh.tg_responses[0])
setSesh(seshid, sesh)
return 'Color and character updated, scripts complete.', f'prep{sesh.found_terms_4_room_items_idx+1}'
#return f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...', f'prep{sesh.found_terms_4_room_items_idx+1}'
else:
setSesh(seshid, sesh)
print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''
def prepItem2ForScript(text, seshid):
sesh = getSesh(seshid)
if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
#generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
generateScriptForItem()
sesh.found_terms_4_room_items_idx += 1
setSesh(seshid, sesh)
return f'prepped{sesh.found_terms_4_room_items_idx}'
else:
setSesh(seshid, sesh)
return f'prep{sesh.found_terms_4_room_items_idx} failed'
def updateItem2Status(text, seshid):
sesh = getSesh(seshid)
if text == f'prepped{sesh.found_terms_4_room_items_idx}':
#print('prepItem1forScript: ', sesh.tg_responses[0])
setSesh(seshid, sesh)
return f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...', f'prep{sesh.found_terms_4_room_items_idx+1}'
else:
print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
setSesh(seshid, sesh)
return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''
def prepItem3ForScript(text, seshid):
sesh = getSesh(seshid)
if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
#generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
generateScriptForItem()
sesh.found_terms_4_room_items_idx += 1
setSesh(seshid, sesh)
return f'prepped{sesh.found_terms_4_room_items_idx}'
else:
setSesh(seshid, sesh)
return f'prep{sesh.found_terms_4_room_items_idx} failed'
def updateItem3Status(text, seshid):
sesh = getSesh(seshid)
if text == f'prepped{sesh.found_terms_4_room_items_idx}':
#print('prepItem1forScript: ', sesh.tg_responses[0])
setSesh(seshid, sesh)
return f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...', f'prep{sesh.found_terms_4_room_items_idx+1}'
else:
print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
setSesh(seshid, sesh)
return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''
def prepItem4ForScript(text, seshid):
sesh = getSesh(seshid)
if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
#generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
generateScriptForItem()
sesh.found_terms_4_room_items_idx += 1
setSesh(seshid, sesh)
return f'prepped{sesh.found_terms_4_room_items_idx}'
else:
setSesh(seshid, sesh)
return f'prep{sesh.found_terms_4_room_items_idx} failed'
def updateItem4Status(text, seshid):
sesh = getSesh(seshid)
if text == f'prepped{sesh.found_terms_4_room_items_idx}':
#print('prepItem1forScript: ', sesh.tg_responses[0])
setSesh(seshid, sesh)
return f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...', f'prep{sesh.found_terms_4_room_items_idx+1}'
else:
print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
setSesh(seshid, sesh)
return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''
def prepItem5ForScript(text, seshid):
sesh = getSesh(seshid)
if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
#generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
generateScriptForItem()
sesh.found_terms_4_room_items_idx += 1
setSesh(seshid, sesh)
return f'prepped{sesh.found_terms_4_room_items_idx}'
else:
setSesh(seshid, sesh)
return f'prep{sesh.found_terms_4_room_items_idx} failed'
def updateItem5Status(text, seshid):
sesh = getSesh(seshid)
if text == f'prepped{sesh.found_terms_4_room_items_idx}':
#print('prepItem1forScript: ', sesh.tg_responses[0])
setSesh(seshid, sesh)
return f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...', f'prep{sesh.found_terms_4_room_items_idx+1}'
else:
print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
setSesh(seshid, sesh)
return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''
def prepItem6ForScript(text, seshid):
sesh = getSesh(seshid)
if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
#generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
generateScriptForItem()
sesh.found_terms_4_room_items_idx += 1
setSesh(seshid, sesh)
return f'prepped{sesh.found_terms_4_room_items_idx}'
else:
setSesh(seshid, sesh)
return f'prep{sesh.found_terms_4_room_items_idx} failed'
def updateItem6Status(text, seshid):
sesh = getSesh(seshid)
if text == f'prepped{sesh.found_terms_4_room_items_idx}':
#print('prepItem1forScript: ', sesh.tg_responses[0])
setSesh(seshid, sesh)
return f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx} of {len(sesh.product_pd_counts)+6}, standby...', f'prep{sesh.found_terms_4_room_items_idx+1}'
else:
print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
setSesh(seshid, sesh)
return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''
def prepItem7ForScript(text, seshid):
sesh = getSesh(seshid)
if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
#generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
generateScriptForItem()
sesh.found_terms_4_room_items_idx += 1
setSesh(seshid, sesh)
return f'prepped{sesh.found_terms_4_room_items_idx}'
else:
setSesh(seshid, sesh)
return f'prep{sesh.found_terms_4_room_items_idx} failed'
def updateItem7Status(text, seshid):
sesh = getSesh(seshid)
if text == f'prepped{sesh.found_terms_4_room_items_idx}':
#print('prepItem1forScript: ', sesh.tg_responses[0])
setSesh(seshid, sesh)
return f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...', f'prep{sesh.found_terms_4_room_items_idx+1}'
else:
print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
setSesh(seshid, sesh)
return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''
def prepItem8ForScript(text, seshid):
sesh = getSesh(seshid)
if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
#generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
generateScriptForItem()
sesh.found_terms_4_room_items_idx += 1
setSesh(seshid, sesh)
return f'prepped{sesh.found_terms_4_room_items_idx}'
else:
setSesh(seshid, sesh)
return f'prep{sesh.found_terms_4_room_items_idx} failed'
def updateItem8Status(text, seshid):
sesh = getSesh(seshid)
if text == f'prepped{sesh.found_terms_4_room_items_idx}':
#print('updateItem8Status: ', sesh.found_terms_4_room_items_idx, len(sesh.found_terms_4_room_items))
sesh.script_status_text = f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...' if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts) else f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for Youtube long-form video.\nWorking on step {sesh.found_terms_4_room_items_idx} of {len(sesh.product_pd_counts)+6}, standby...'
setSesh(seshid, sesh)
return sesh.script_status_text, f'prep{sesh.found_terms_4_room_items_idx+1}'
else:
print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
setSesh(seshid, sesh)
return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''
def prepItem9ForScript(text, seshid):
sesh = getSesh(seshid)
if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): generateScriptForItem() #generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): sesh.found_terms_4_room_items_idx += 1
setSesh(seshid, sesh)
return f'prepped{sesh.found_terms_4_room_items_idx}'
else:
setSesh(seshid, sesh)
return f'prep{sesh.found_terms_4_room_items_idx} failed'
def updateItem9Status(text, seshid):
sesh = getSesh(seshid)
if text == f'prepped{sesh.found_terms_4_room_items_idx}':
#print('updateItem9Status: ', sesh.found_terms_4_room_items_idx, len(sesh.found_terms_4_room_items))
sesh.script_status_text = f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...' if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts)-1 else sesh.script_status_text
setSesh(seshid, sesh)
return sesh.script_status_text, f'prep{sesh.found_terms_4_room_items_idx+1}'
else:
print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
setSesh(seshid, sesh)
return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''
def prepItem10ForScript(text, seshid):
sesh = getSesh(seshid)
if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): generateScriptForItem() #generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): sesh.found_terms_4_room_items_idx += 1
setSesh(seshid, sesh)
return f'prepped{sesh.found_terms_4_room_items_idx}'
else:
setSesh(seshid, sesh)
return f'prep{sesh.found_terms_4_room_items_idx} failed'
def updateItem10Status(text, seshid):
sesh = getSesh(seshid)
if text == f'prepped{sesh.found_terms_4_room_items_idx}':
#print('updateItem10Status: ', sesh.found_terms_4_room_items_idx, len(sesh.found_terms_4_room_items))
sesh.script_status_text = f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...' if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts)-1 else sesh.script_status_text
setSesh(seshid, sesh)
return sesh.script_status_text, f'prep{sesh.found_terms_4_room_items_idx+1}'
else:
print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
setSesh(seshid, sesh)
return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''
def prepItem11ForScript(text, seshid):
sesh = getSesh(seshid)
if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): generateScriptForItem() #generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): sesh.found_terms_4_room_items_idx += 1
setSesh(seshid, sesh)
return f'prepped{sesh.found_terms_4_room_items_idx}'
else:
setSesh(seshid, sesh)
return f'prep{sesh.found_terms_4_room_items_idx} failed'
def updateItem11Status(text, seshid):
sesh = getSesh(seshid)
if text == f'prepped{sesh.found_terms_4_room_items_idx}':
#print('updateItem11Status: ', sesh.found_terms_4_room_items_idx, len(sesh.found_terms_4_room_items))
sesh.script_status_text = f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...' if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts)-1 else sesh.script_status_text
setSesh(seshid, sesh)
return sesh.script_status_text, f'prep{sesh.found_terms_4_room_items_idx+1}'
else:
print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
setSesh(seshid, sesh)
return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''
def prepItem12ForScript(text, seshid):
sesh = getSesh(seshid)
if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): generateScriptForItem() #generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): sesh.found_terms_4_room_items_idx += 1
setSesh(seshid, sesh)
return f'prepped{sesh.found_terms_4_room_items_idx}'
else:
setSesh(seshid, sesh)
return f'prep{sesh.found_terms_4_room_items_idx} failed'
def updateItem12Status(text, seshid):
sesh = getSesh(seshid)
if text == f'prepped{sesh.found_terms_4_room_items_idx}':
#print('updateItem12Status: ', sesh.found_terms_4_room_items_idx, len(sesh.found_terms_4_room_items))
sesh.script_status_text = f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...' if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts)-1 else sesh.script_status_text
setSesh(seshid, sesh)
return sesh.script_status_text, f'prep{sesh.found_terms_4_room_items_idx+1}'
else:
print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
setSesh(seshid, sesh)
return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''
def prepItem13ForScript(text, seshid):
sesh = getSesh(seshid)
if text == f'prep{sesh.found_terms_4_room_items_idx+1}':
if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): generateScriptForItem() #generateScriptForItem(sesh.found_terms_4_room_items_idx,sesh.found_terms_4_room_items[sesh.found_terms_4_room_items_idx])
if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts): sesh.found_terms_4_room_items_idx += 1
setSesh(seshid, sesh)
return f'prepped{sesh.found_terms_4_room_items_idx}'
else:
setSesh(seshid, sesh)
return f'prep{sesh.found_terms_4_room_items_idx} failed'
def updateItem13Status(text, seshid):
sesh = getSesh(seshid)
if text == f'prepped{sesh.found_terms_4_room_items_idx}':
#print('updateItem13Status: ', sesh.found_terms_4_room_items_idx, len(sesh.found_terms_4_room_items))
#print('prepItem13forScript: ', sesh.tg_responses)
sesh.scripts['Base'] = '\n\n'.join(sesh.tg_responses)
sesh.script_status_text = f'{sesh.product_pd_counts[sesh.found_terms_4_room_items_idx-1][0].upper()} script complete.\nPreparing script for {sesh.product_pd_counts[sesh.found_terms_4_room_items_idx][0]}.\nWorking on step {sesh.found_terms_4_room_items_idx+1} of {len(sesh.product_pd_counts)+6}, standby...' if sesh.found_terms_4_room_items_idx < len(sesh.product_pd_counts)-1 else sesh.script_status_text
setSesh(seshid, sesh)
return sesh.script_status_text, 'prep_ytlong'
else:
print(f'prepItem{sesh.found_terms_4_room_items_idx+1}ForScript: fail')
setSesh(seshid, sesh)
return f'ITEM {sesh.found_terms_4_room_items_idx} prep failed', ''
def prepYTLongFormScript(text, seshid):
sesh = getSesh(seshid)
if text == 'prep_ytlong':
prompt = 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a long-form Youtube video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.'
sesh.scripts['Youtube Long-Form'] = getTextGen(prompt) #client.text_generation(prompt, model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
setSesh(seshid, sesh)
return 'ytlong_prepped'
else:
setSesh(seshid, sesh)
return 'prep_ytlong failed'
def updateYTLongFormStatus(text, seshid):
sesh = getSesh(seshid)
if text == 'ytlong_prepped':
print('updateYTLongFormStatus: ', list(sesh.scripts))
setSesh(seshid, sesh)
return f'YOUTUBE LONG-FORM script complete.\nPreparing script for Youtube short-form.\nWorking on step {sesh.found_terms_4_room_items_idx+2} of {len(sesh.product_pd_counts)+6}, standby...', 'prep_ytshort', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
else:
setSesh(seshid, sesh)
return 'YT long-form script failed', '', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
def prepYTShortFormScript(text, seshid):
sesh = getSesh(seshid)
if text == 'prep_ytshort':
prompt = 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a Youtube Short. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.'
sesh.scripts['Youtube Short-Form'] = getTextGen(prompt) #client.text_generation(prompt, model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
setSesh(seshid, sesh)
return 'ytshort_prepped'
else:
setSesh(seshid, sesh)
return 'prep_ytshort failed'
def updateYTShortFormStatus(text, seshid):
sesh = getSesh(seshid)
print('updateYTShortFormStatus: ', text, list(sesh.scripts))
if text == 'ytshort_prepped':
setSesh(seshid, sesh)
return f'YOUTUBE SHORT script complete.\nPreparing script for Facebook.\nWorking on step {sesh.found_terms_4_room_items_idx+3} of {len(sesh.product_pd_counts)+6}, standby...', 'prepfb', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
else:
setSesh(seshid, sesh)
return 'YT short-form script failed', '', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
def prepFBScript(text,seshid):
sesh = getSesh(seshid)
if text == 'prepfb':
prompt = 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a long-form Facebook video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.'
sesh.scripts['Facebook Long-Form'] = getTextGen(prompt) #client.text_generation(prompt, model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
setSesh(seshid, sesh)
return 'fb_prepped'
else:
setSesh(seshid, sesh)
return 'prepfb failed'
def updateFBStatus(text, seshid):
sesh = getSesh(seshid)
print('updateFBStatus: ', text, list(sesh.scripts))
if text == 'fb_prepped':
setSesh(seshid, sesh)
return f'FACEBOOK script complete.\nPreparing script for Instagram Reel.\nWorking on step {sesh.found_terms_4_room_items_idx+4} of {len(sesh.product_pd_counts)+6}, standby...', 'prepig', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
else:
setSesh(seshid, sesh)
return 'Facebook script failed', '', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
def prepIGScript(text, seshid):
if text == 'prepig':
prompt = 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for an Instagram Reel video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.'
sesh.scripts['Instagram Reel'] = getTextGen(prompt) #client.text_generation(prompt, model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
return 'ig_prepped'
else:
return 'prepig failed'
def updateIGStatus(text, seshid):
print('updateIGStatus: ', text, list(sesh.scripts))
if text == 'ig_prepped':
return f'INSTAGRAM REEL script complete.\nPreparing script for TikTok.\nWorking on step {sesh.found_terms_4_room_items_idx+5} of {len(sesh.product_pd_counts)+6}, standby...', 'prep_tiktok', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
else:
return 'IG script failed', '', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
def prepTikTokScript(text, seshid):
if text == 'prep_tiktok':
prompt = 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a Tiktok video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.'
sesh.scripts['Tiktok'] = getTextGen(prompt) #client.text_generation(prompt, model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
return 'tiktok_prepped'
else:
return 'prep_tiktok failed'
def updateTikTokStatus(text, seshid):
print('updateTikTokStatus: ', text, list(sesh.scripts))
if text == 'tiktok_prepped':
return f'TIKTOK script complete.\nPreparing script for LinkedIn.\nWorking on step {sesh.found_terms_4_room_items_idx+6} of {len(sesh.product_pd_counts)+6}, standby...', 'prep_linkedin', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
else:
return 'TikTok script failed', '', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
def prepLinkedInScript(text, seshid):
if text == 'prep_linkedin':
prompt = 'SCRIPT: \n\n'+'\n\n'.join(sesh.tg_responses)+f'\n\nTASK: rewrite the provided SCRIPT for a LinkedIn long-form video. Keep in mind the SCRIPT is about reviewing items to potentially have purchased, shipped and decorate a {sesh.room_type}; this is all for a prospective home buyer -- you are the item reviewer who is reviewing items on behalf of the potential home buyer.'
sesh.scripts['LinkedIn'] = getTextGen(prompt) #client.text_generation(prompt, model="mistralai/Mixtral-8x7B-Instruct-v0.1", max_new_tokens=2500)
return 'linkedin_prepped'
else:
return 'prep_linkedin failed'
def updateLinkedInStatus(text, seshid):
print('updateLinkedInStatus: ', text, list(sesh.scripts))
if text == 'linkedin_prepped':
return 'All scripts complete.', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
else:
return 'LinkedIn script failed', gr.Dropdown(list(sesh.scripts), label='Scripts', interactive=True)
def selectScript(evt: gr.SelectData, seshid):
sesh = getSesh(seshid)
script = evt.value
frmt = evt.value
if frmt == 'Status':
return 'Select a video format to have a script prepared.'
uploadToScriptGenPromise(frmt, seshid)
#frmt_id_maps[formats[i]]
url = 'https://dreamdemo.pythonanywhere.com/query_textgen'
#item_locator_data = [tuple(sesh.item_data_[sesh.current_img_signature][sesh.room_type][sesh.room_style][sesh.price][sesh.Palette_ids[sesh.current_img_signature]][data[1]][data[0]]) for data in sesh.display_items_[sesh.current_img_signature] if data[1] not in ['Palette', 'Living Room', 'Bedroom']]
#valid_data = {'item_locator_data': item_locator_data}
valid_data = {'seshid':seshid, 'genuid': sesh.frmt_id_maps[sesh.current_img_signature][frmt]}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
start = time.time()
#r = requests.post(url, data=json.dumps(valid_data), headers=headers)
#jsondata = json.loads(r.content)
urls = ['https://dreamdemo.pythonanywhere.com/query_textgen' for i in range(1)]
headers = [{'Content-type': 'application/json', 'Accept': 'text/plain'} for i in range(1)]
json_data = [json.dumps({'seshid':seshid, 'genuid': sesh.frmt_id_maps[sesh.current_img_signature][frmt]}) for i in range(1)]
responses = asyncio.run(main_post(urls, headers, json_data, timeout=2))
try:
data_dict = json.loads(responses[0])
except:
data_dict = {}
print('selectScript: ', frmt, sesh.frmt_id_maps[sesh.current_img_signature][frmt], time.time()-start, responses)
#return sesh.scripts[script]
return 'Script being generated. Try again in 30 seconds.' if not data_dict or 'text' not in data_dict else data_dict['text']
def showMainDisplay(home_address):
print('showMainDisplay: ', home_address)
return gr.update(visible=bool(0)), gr.update(visible=bool(1))
with gr.Blocks(theme=gr.themes.Monochrome(), js=js_func) as demo:
ads = gr.Label('EndlessIdeas: Helping Your Ideas Find A Home', label='Sponsors')
with gr.Tab('Update Property Data'):
with gr.Row():
with gr.Column():
upload = gr.Image(label='Upload Room Photo')
upload_photo = gr.Button('Submit Photo')
with gr.Column():
working_room = gr.Gallery(label='Select Working Room', height=350, interactive=True)
with gr.Tab('Room Type'):
with gr.Row():
with gr.Column():
working_room2 = gr.Image(label='Working Room')
with gr.Column():
rooms_gallery = gr.Gallery([(v,k) for k,v in bedrooms.items()], label="Room Type", height=350, interactive=True)
with gr.Tab('Design Style'):
with gr.Row():
with gr.Column():
working_room3 = gr.Image(label='Working Room')
with gr.Column():
design_gallery = gr.Gallery(label="Design Styles", preview=True, height=350, interactive=True)
price_radio = gr.Radio(['Affordable', 'Upmarket'], label='Price Point', interactive=True, visible=True, value='Affordable')
bedsize_radio = gr.Radio(['Full', 'Queen', 'King'], value='Queen', label='Bed Size', interactive=True, visible=False)
with gr.Tab('Color Palette'):
with gr.Row():
with gr.Column():
working_room1 = gr.Image(label='Working Room')
with gr.Column():
color_Palettes = gr.Gallery(label='Proposed Color Palettes', height=350, interactive=True)
with gr.Tab('Room Items'):
with gr.Row():
room_items = gr.Gallery(label='Room Items', height=350, interactive=True)
with gr.Tab('Item Replace'):
with gr.Row():
with gr.Column():
working_Palette = gr.Image(label='Working Color Palette')
with gr.Column():
esdsd = gr.Gallery(label='Proposed Color Palettes', height=350, interactive=True)
with gr.Tab('Shopping Cart'):
pass
#home_address, address_enter, showMainDisplay
with gr.Blocks(theme=gr.themes.Monochrome(), js=js_func, css=css) as demo:
#ads = gr.Image("C:\\Users\\Wayne\\Downloads\\Welcome Home.gif", show_label=False, scale=5, height=150, show_download_button=False)
ads = gr.Label("Dream Home: As Quick As A Click. As Simple As Shopping. ", show_label=False)
seshid = gr.Textbox('SESHID', visible=False)
replace = gr.Gallery(label='Replacement Items', rows=2, columns=7, visible=False, interactive=True, elem_classes=['scroll'])
with gr.Row(visible=False) as store_summary:
merchant_top = gr.Label(label='Merchant')
total = gr.Label(label='Number of Items')
num_of_items = gr.Label(label='Total')
with gr.Row() as landing_page:
merchant_top = gr.Label(label="Let's Get Started")
home_address = gr.Textbox()
address_enter = gr.Button('Go')
with gr.Row(visible=False) as main_display:
with gr.Column(scale=5) as items_display:
#room_items = gr.Gallery([((sesh.Palette_img if item == 'Palette' else sesh.default_img ) if item in ['Palette', 'Living Room', 'Bedroom'] else room_item_placeholder_images_dict['LIVING ROOM FURNITURE'][item], item) for item in living_layout_new], label='Room Items', columns=5, height=400, interactive=True)
room_items = gr.Gallery([((Palette_img if item == 'Palette' else default_img ) if item in ['Palette', 'Living Room', 'Bedroom'] else room_item_placeholder_images_dict['LIVING ROOM FURNITURE'][item], item) for item in living_layout_new], label='Room Items', columns=5, height=400, elem_classes=['scroll'])
with gr.Column(scale=1, visible=False) as style_side:
#dsdf = gr.Image("C:\\Users\\Wayne\\Downloads\\agent-first.gif", show_label=False, show_download_button=False)
close1 = gr.Button('Close')
with gr.Column(scale=1, visible=False) as item_side:
merchant = gr.Label('No Item Selected', label='Merchant')
replace_item = gr.Button('Replace')
#sdsd = gr.Image("C:\\Users\\Wayne\\Downloads\\agent-first.gif", show_label=False, show_download_button=False)
close2 = gr.Button('Close')
#with gr.Group():
#with gr.Row():
#exclude = gr.Button('Exclude')
#include = gr.Button('Include')
#Palette_ref = gr.Image(show_label=False)
#replace = gr.Gallery(label='Replacement Items', columns=2)
with gr.Column(scale=1, visible=False) as room_side:
close3 = gr.Button('Close')
summary_button = gr.Button('Summarise')
with gr.Group(visible=False) as summary_group:
with gr.Accordion(label='Merchant Summary') as merchant_summary:
complete_summary = gr.Radio(['Complete', 'Merchant', 'Script'], value='Complete', interactive=True, label='Inspection')
store_dropdown = gr.Dropdown(label='Merchants', visible=False)
with gr.Row(equal_height=True) as budget_row:
budget = gr.Textbox(label='Budget', min_width=70)
#budget_button = gr.Button('Update', size='sm')
complete_source_breakdown = gr.Textbox(label='Item Breakdown', interactive=True)
with gr.Accordion(label='Product Summary', open=False, visible=False) as product_summary:
product_dropdown = gr.Dropdown(label='Products')
count = gr.Number(label='Item Count', minimum=0)
source = gr.Markdown(label='Source')
#room_ad = gr.Image("C:\\Users\\Wayne\\Downloads\\list with us.gif", show_label=False, show_download_button=False)
room_ad = gr.Textbox(visible=False)
with gr.Accordion(label='Select Design Style', open=False) as design_accordion:
design_gallery = gr.Gallery(design_images, label="Design Styles", preview=True, interactive=True, height=200, elem_classes=['scroll'])
price_radio = gr.Radio(['Affordable', 'Upmarket'], label='Price Point', interactive=True, visible=True, value='Affordable')
bedsize_radio = gr.Radio(['Full', 'Queen', 'King'], value='Queen', label='Bed Size', interactive=True, visible=True)
with gr.Accordion(label='Update Property Data', open=False) as update_accordion:
with gr.Accordion(label='Upload Photo', open=False):
upload = gr.Image(label='Upload Room Photo', height=200)
upload_photo = gr.Button('Submit Photo')
with gr.Accordion(label='Select Room', open=False):
choose_room = gr.Gallery(label="Room To Decorate", height=200, interactive=True)
with gr.Accordion(label='Select Room Type', open=False):
room2decorate = gr.Image(label='Working Room', height=150)
rooms_gallery = gr.Gallery([(v,k) for k,v in bedrooms.items()], label="Room Type", interactive=True)
with gr.Column(scale=1, visible=False) as colors_side:
#close4 = gr.Button('Close')
with gr.Row():
close4 = gr.Button('Close', size='sm')
with gr.Row():
palettes = gr.Button('Palettes', size='sm', min_width=45)
scripts = gr.Button('Scripts', size='sm', min_width=45)
journeys = gr.Button('Journeys', size='sm', min_width=45)
#dsdsd = gr.Image("C:\\Users\\Wayne\\Downloads\\local ad.gif", show_label=False, show_download_button=False)
with gr.Group(visible=True) as palettes_div:
color_Palettes = gr.Gallery(label='Proposed Color Palettes', columns=2, height=200, elem_classes=['scroll'])
with gr.Group(visible=False) as script_div:
status_text = gr.Textbox("loading info for color and character\nstand by...\n", show_label=True, interactive=False, lines=3, label='Status', visible=False)
scripts_drop = gr.Dropdown(['Status', 'Youtube Long-Form', 'Youtube Short-Form', 'Facebook Long-Form', 'Instagram Reel', 'Tik Tok', 'LinkedIn'], label='Scripts', interactive=True)
script_display = gr.Textbox(label='Script', max_lines=7)
script_broker = gr.Textbox(visible=False)
item_links_load = gr.Textbox(visible=False)
item_links_search = gr.Textbox(visible=False)
script_load1 = gr.Textbox(visible=False)
script_load2 = gr.Textbox(visible=False)
script_load3 = gr.Textbox(visible=False)
script_load4 = gr.Textbox(visible=False)
script_load5 = gr.Textbox(visible=False)
script_load6 = gr.Textbox(visible=False)
script_load7 = gr.Textbox(visible=False)
script_load8 = gr.Textbox(visible=False)
script_load9 = gr.Textbox(visible=False)
script_load10 = gr.Textbox(visible=False)
script_load11 = gr.Textbox(visible=False)
script_load12 = gr.Textbox(visible=False)
script_load13 = gr.Textbox(visible=False)
yt_load = gr.Textbox(visible=False)
linkedin_load = gr.Textbox(visible=False)
facebook_load = gr.Textbox(visible=False)
ytshorts_load = gr.Textbox(visible=False)
reels_load = gr.Textbox(visible=False)
tiktok_load = gr.Textbox(visible=False)
item_links_load_update = gr.Textbox(visible=False)
item_links_search_update = gr.Textbox(visible=False)
all_items_update = gr.Textbox(visible=False)
script_load1_update = gr.Textbox(visible=False)
script_load2_update = gr.Textbox(visible=False)
script_load3_update = gr.Textbox(visible=False)
script_load4_update = gr.Textbox(visible=False)
script_load5_update = gr.Textbox(visible=False)
script_load6_update = gr.Textbox(visible=False)
script_load7_update = gr.Textbox(visible=False)
script_load8_update = gr.Textbox(visible=False)
script_load9_update = gr.Textbox(visible=False)
script_load10_update = gr.Textbox(visible=False)
script_load11_update = gr.Textbox(visible=False)
script_load12_update = gr.Textbox(visible=False)
script_load13_update = gr.Textbox(visible=False)
yt_update = gr.Textbox(visible=False)
linkedin_update = gr.Textbox(visible=False)
facebook_update = gr.Textbox(visible=False)
ytshorts_update = gr.Textbox(visible=False)
reels_update = gr.Textbox(visible=False)
tiktok_update = gr.Textbox(visible=False)
dummy = gr.Textbox(visible=False)
with gr.Group(visible=False) as journeys_div:
with gr.Accordion('Dream Job', open=False):
dream_job_title = gr.Textbox(label="Dream Job Title")
dream_job_company = gr.Textbox(label="Dream Job Company")
dream_job_salary = gr.Number(label="Dream Job Salary")
dream_job_skills = gr.Textbox(label="Dream Job Required Skills")
current_skills = gr.Textbox(label="Current Skills")
with gr.Accordion('Dream Home', open=False):
dream_home_location = gr.Textbox(label="Dream Home Location")
dream_home_price = gr.Number(label="Dream Home Price")
dream_home_size = gr.Textbox(label="Dream Home Size")
dream_home_features = gr.Textbox(label="Dream Home Features")
current_savings = gr.Number(label="Current Savings")
# Output components
job_progress_textbox = gr.Textbox(label="Progress Towards Dream Job")
home_progress_textbox = gr.Textbox(label="Progress Towards Dream Home")
address_enter.click(showMainDisplay, [home_address], [landing_page, main_display])
palettes.click(showPalettes, [seshid], [palettes_div, script_div, journeys_div])
scripts.click(showScripts, [seshid], [palettes_div, script_div, journeys_div, item_links_load])
journeys.click(showJourneys, [seshid], [palettes_div, script_div, journeys_div])
item_links_load.change(loadColorAndCharacter, [item_links_load, seshid], [item_links_load_update])
item_links_load_update.change(updateLinksLoadStatus, [item_links_load_update, seshid], [status_text, item_links_search])
item_links_search.change(searchColorAndCharacter, [item_links_search, seshid], [item_links_search_update])
item_links_search_update.change(updateLinksSearchStatus, [item_links_search_update, seshid], [status_text, script_load1])
script_load1.change(prepAllScripts, [script_load1, seshid], [all_items_update])
all_items_update.change(updateAllItemsStatus, [all_items_update, seshid], [status_text, scripts_drop])
#script_load1.change(prepItem1ForScript, script_load1, [script_load1_update])
script_load1_update.change(updateItem1Status, [script_load1_update, seshid], [status_text, script_load2])
script_load2.change(prepItem2ForScript, [script_load2, seshid], [script_load2_update])
script_load2_update.change(updateItem1Status, [script_load2_update, seshid], [status_text, script_load3])
script_load3.change(prepItem3ForScript, [script_load3, seshid], [script_load3_update])
script_load3_update.change(updateItem3Status, [script_load3_update, seshid], [status_text, script_load4])
script_load4.change(prepItem4ForScript, [script_load4, seshid], [script_load4_update])
script_load4_update.change(updateItem4Status, [script_load4_update, seshid], [status_text, script_load5])
script_load5.change(prepItem5ForScript, [script_load5, seshid], [script_load5_update])
script_load5_update.change(updateItem5Status, [script_load5_update, seshid], [status_text, script_load6])
script_load6.change(prepItem6ForScript, [script_load6, seshid], [script_load6_update])
script_load6_update.change(updateItem6Status, [script_load6_update, seshid], [status_text, script_load7])
script_load7.change(prepItem7ForScript, [script_load7, seshid], [script_load7_update])
script_load7_update.change(updateItem7Status, [script_load7_update, seshid], [status_text, script_load8])
script_load8.change(prepItem8ForScript, [script_load8, seshid], [script_load8_update])
script_load8_update.change(updateItem8Status, [script_load8_update, seshid], [status_text, script_load9])
script_load9.change(prepItem9ForScript, [script_load9, seshid], [script_load9_update])
script_load9_update.change(updateItem9Status, [script_load9_update, seshid], [status_text, script_load10])
script_load10.change(prepItem10ForScript, [script_load10, seshid], [script_load10_update])
script_load10_update.change(updateItem10Status, [script_load10_update, seshid], [status_text, script_load11])
script_load11.change(prepItem11ForScript, [script_load11, seshid], [script_load11_update])
script_load11_update.change(updateItem11Status, [script_load11_update, seshid], [status_text, script_load12])
script_load12.change(prepItem12ForScript, [script_load12, seshid], [script_load12_update])
script_load12_update.change(updateItem12Status, [script_load12_update, seshid], [status_text, script_load13])
script_load13.change(prepItem13ForScript, [script_load13, seshid], [script_load13_update])
script_load13_update.change(updateItem13Status, [script_load13_update, seshid], [status_text, yt_load])
yt_load.change(prepYTLongFormScript, [yt_load, seshid], [yt_update])
yt_update.change(updateYTLongFormStatus, [yt_update, seshid], [status_text, ytshorts_load, scripts_drop])
ytshorts_load.change(prepYTShortFormScript, [ytshorts_load, seshid], [ytshorts_update])
ytshorts_update.change(updateYTShortFormStatus, [ytshorts_update, seshid], [status_text, facebook_load, scripts_drop])
facebook_load.change(prepFBScript, [facebook_load, seshid], [facebook_update])
facebook_update.change(updateFBStatus, [facebook_update, seshid], [status_text, reels_load, scripts_drop])
reels_load.change(prepIGScript, [reels_load, seshid], [reels_update])
reels_update.change(updateIGStatus, [reels_update, seshid], [status_text, tiktok_load, scripts_drop])
tiktok_load.change(prepTikTokScript, [tiktok_load, seshid], [tiktok_update])
tiktok_update.change(updateTikTokStatus, [tiktok_update, seshid], [status_text, linkedin_load, scripts_drop])
linkedin_load.change(prepLinkedInScript, [linkedin_load, seshid], [linkedin_update])
linkedin_update.change(updateLinkedInStatus, [linkedin_update, seshid], [status_text, scripts_drop])
scripts_drop.select(selectScript, [seshid], script_display)
room_items.select(roomItemClick, seshid, [items_display, item_side, room_side, colors_side, replace, ads, store_summary, seshid])
close1.click(closeSidePanel, [seshid], [items_display, item_side, room_side, colors_side, merchant, replace, ads, store_summary])
close2.click(closeSidePanel, [seshid], [items_display, item_side, room_side, colors_side, merchant, replace, ads, store_summary])
close3.click(closeSidePanel, [seshid], [items_display, item_side, room_side, colors_side, merchant, replace, ads, store_summary])
close4.click(closeSidePanel, [seshid], [items_display, item_side, room_side, colors_side, merchant, replace, ads, store_summary])
upload_photo.click(submitPhoto, [upload, choose_room, seshid], [choose_room, upload, seshid])
#choose_room.select(makePalettes, None, [color_Palettes, room2decorate, room_items])
choose_room.select(makePalettes, [seshid], [color_Palettes, room2decorate, room_items])
#upload_photo.click(submitPhoto, upload, [working_room, upload])
#working_room.select(makePalettes, None, [working_room1, color_Palettes])
#working_room.select(makePalettes, None, [working_room1, working_room2, working_room3, color_Palettes, room_items])
working_room.select(makePalettes, seshid, [working_room1, working_room2, working_room3, color_Palettes, room_items])
#rooms_gallery.select(set_style, None, [design_gallery, bedsize_radio, room_items])
rooms_gallery.select(updateRoomType, seshid, [design_gallery, bedsize_radio, room_items])
#color_Palettes.select(set_Palette, None, None)
color_Palettes.select(updateColors, seshid, [room_items])
design_gallery.select(updateStyle, seshid, room_items)
price_radio.select(updatePrice, seshid, room_items)
bedsize_radio.select(updateBedsize, seshid, room_items)
replace.select(productClick, [seshid], merchant)
replace_item.click(replaceProduct, [seshid], [items_display, item_side, room_side, colors_side, merchant, replace, ads, room_items])
#summary_button.click(summarisePerStore, None, None)
summary_button.click(summaryClick, [seshid], [summary_button, design_accordion, update_accordion, room_ad, summary_group, replace, ads, store_summary, store_dropdown, merchant_top, total, num_of_items, complete_source_breakdown])
store_dropdown.select(selectMerchantProduct, [seshid], [product_dropdown, merchant_top, total, num_of_items])
complete_summary.select(changeSummaryFilter, [seshid], [merchant_top, total, num_of_items, product_summary, complete_source_breakdown, budget_row, store_dropdown])
product_dropdown.select(displaySource, [seshid], [source, count])
count.change(updateProductCount, [count, seshid], [total, num_of_items])
budget.submit(updateBudget, [budget, seshid], [room_items, total, num_of_items])
demo.launch()