Skip to content

Commit

Permalink
Move ui lib to gooey_gui package, rename gooey_ui to gooey_gui for co…
Browse files Browse the repository at this point in the history
…nsistency
  • Loading branch information
devxpy committed Jul 27, 2024
1 parent 4652096 commit b0c80da
Show file tree
Hide file tree
Showing 93 changed files with 2,163 additions and 4,018 deletions.
18 changes: 8 additions & 10 deletions celeryapp/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
from time import time
from types import SimpleNamespace

import gooey_gui as gui
import requests
import sentry_sdk
from django.db.models import Sum
from django.utils import timezone
from fastapi import HTTPException

import gooey_ui as st
from app_users.models import AppUser, AppUserTransaction
from bots.admin_links import change_obj_url
from bots.models import SavedRun, Platform, Workflow
Expand All @@ -22,8 +22,6 @@
from daras_ai_v2.exceptions import UserError
from daras_ai_v2.send_email import send_email_via_postmark, send_low_balance_email
from daras_ai_v2.settings import templates
from gooey_ui.pubsub import realtime_push
from gooey_ui.state import set_query_params
from gooeysite.bg_db_conn import db_middleware
from payments.auto_recharge import (
should_attempt_auto_recharge,
Expand Down Expand Up @@ -69,28 +67,28 @@ def save_on_step(yield_val: str | tuple[str, dict] = None, *, done: bool = False
# extract outputs from local state
| {
k: v
for k, v in st.session_state.items()
for k, v in gui.session_state.items()
if k in page.ResponseModel.__fields__
}
# add extra outputs from the run
| extra_output
)

# send outputs to ui
realtime_push(channel, output)
gui.realtime_push(channel, output)
# save to db
page.dump_state_to_sr(st.session_state | output, sr)
page.dump_state_to_sr(gui.session_state | output, sr)

user = AppUser.objects.get(id=user_id)
page = page_cls(request=SimpleNamespace(user=user))
page.setup_sentry()
sr = page.run_doc_sr(run_id, uid)
st.set_session_state(sr.to_dict() | (unsaved_state or {}))
set_query_params(dict(run_id=run_id, uid=uid))
gui.set_session_state(sr.to_dict() | (unsaved_state or {}))
gui.set_query_params(dict(run_id=run_id, uid=uid))

try:
save_on_step()
for val in page.main(sr, st.session_state):
for val in page.main(sr, gui.session_state):
save_on_step(val)

# render errors nicely
Expand All @@ -107,7 +105,7 @@ def save_on_step(yield_val: str | tuple[str, dict] = None, *, done: bool = False

# run completed successfully, deduct credits
else:
sr.transaction, sr.price = page.deduct_credits(st.session_state)
sr.transaction, sr.price = page.deduct_credits(gui.session_state)

# save everything, mark run as completed
finally:
Expand Down
2 changes: 1 addition & 1 deletion components_doc.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import inspect
from functools import wraps

import gooey_ui as gui
import gooey_gui as gui

META_TITLE = "Gooey Components"
META_DESCRIPTION = "Explore the Gooey Component Library"
Expand Down
2 changes: 1 addition & 1 deletion conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def mock_celery_tasks():
with (
patch("celeryapp.tasks.runner_task", _mock_runner_task),
patch("celeryapp.tasks.post_runner_tasks", _mock_post_runner_tasks),
patch("daras_ai_v2.bots.realtime_subscribe", _mock_realtime_subscribe),
patch("gooey_gui.realtime_subscribe", _mock_realtime_subscribe),
):
yield

Expand Down
72 changes: 36 additions & 36 deletions daras_ai_v2/analysis_results.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@

from django.db.models import IntegerChoices

import gooey_ui as st
import gooey_gui as gui
from app_users.models import AppUser
from bots.models import BotIntegration, Message
from daras_ai_v2.base import RecipeTabs
from daras_ai_v2.copy_to_clipboard_button_widget import copy_to_clipboard_button
from daras_ai_v2.grid_layout_widget import grid_layout
from daras_ai_v2.workflow_url_input import del_button
from gooey_ui import QueryParamsRedirectException
from gooey_gui import QueryParamsRedirectException
from gooeysite.custom_filters import related_json_field_summary
from recipes.BulkRunner import list_view_editor
from recipes.VideoBots import VideoBotsPage
Expand Down Expand Up @@ -41,7 +41,7 @@ def render_analysis_results_page(
render_title_breadcrumb_share(bi, current_url, current_user)

if title:
st.write(title)
gui.write(title)

if graphs_json:
graphs = json.loads(graphs_json)
Expand All @@ -55,48 +55,48 @@ def render_analysis_results_page(
except Message.DoesNotExist:
results = None
if not results:
with st.center():
st.error("No analysis results found")
with gui.center():
gui.error("No analysis results found")
return

with st.div(className="pb-5 pt-3"):
with gui.div(className="pb-5 pt-3"):
grid_layout(2, graphs, partial(render_graph_data, bi, results), separator=False)

st.checkbox("🔄 Refresh every 10s", key="autorefresh")
gui.checkbox("🔄 Refresh every 10s", key="autorefresh")

with st.expander("✏️ Edit"):
title = st.text_area("##### Title", value=title)
with gui.expander("✏️ Edit"):
title = gui.text_area("##### Title", value=title)

st.session_state.setdefault("selected_graphs", graphs)
gui.session_state.setdefault("selected_graphs", graphs)
selected_graphs = list_view_editor(
add_btn_label="➕ Add a Graph",
key="selected_graphs",
render_inputs=partial(render_inputs, results),
)

with st.center():
if st.button("✅ Update"):
with gui.center():
if gui.button("✅ Update"):
_on_press_update(title, selected_graphs)


def render_inputs(results: dict, key: str, del_key: str, d: dict):
ocol1, ocol2 = st.columns([11, 1], responsive=False)
ocol1, ocol2 = gui.columns([11, 1], responsive=False)
with ocol1:
col1, col2, col3 = st.columns(3)
col1, col2, col3 = gui.columns(3)
with ocol2:
ocol2.node.props["style"] = dict(paddingTop="2rem")
del_button(del_key)

with col1:
d["key"] = st.selectbox(
d["key"] = gui.selectbox(
label="##### Key",
options=results.keys(),
key=f"{key}_key",
value=d.get("key"),
)
with col2:
col2.node.props["style"] = dict(paddingTop="0.45rem")
d["graph_type"] = st.selectbox(
d["graph_type"] = gui.selectbox(
label="###### Graph Type",
options=[g.value for g in GraphType],
format_func=lambda x: GraphType(x).label,
Expand All @@ -105,7 +105,7 @@ def render_inputs(results: dict, key: str, del_key: str, d: dict):
)
with col3:
col3.node.props["style"] = dict(paddingTop="0.45rem")
d["data_selection"] = st.selectbox(
d["data_selection"] = gui.selectbox(
label="###### Data Selection",
options=[d.value for d in DataSelection],
format_func=lambda x: DataSelection(x).label,
Expand All @@ -115,10 +115,10 @@ def render_inputs(results: dict, key: str, del_key: str, d: dict):


def _autorefresh_script():
if not st.session_state.get("autorefresh"):
if not gui.session_state.get("autorefresh"):
return
st.session_state.pop("__cache__", None)
st.js(
gui.session_state.pop("__cache__", None)
gui.js(
# language=JavaScript
"""
setTimeout(() => {
Expand All @@ -139,23 +139,23 @@ def render_title_breadcrumb_share(
else:
run_title = bi.saved_run.page_title # this is mostly for backwards compat
query_params = dict(run_id=bi.saved_run.run_id, uid=bi.saved_run.uid)
with st.div(className="d-flex justify-content-between mt-4"):
with st.div(className="d-lg-flex d-block align-items-center"):
with st.tag("div", className="me-3 mb-1 mb-lg-0 py-2 py-lg-0"):
with st.breadcrumbs():
with gui.div(className="d-flex justify-content-between mt-4"):
with gui.div(className="d-lg-flex d-block align-items-center"):
with gui.tag("div", className="me-3 mb-1 mb-lg-0 py-2 py-lg-0"):
with gui.breadcrumbs():
metadata = VideoBotsPage.workflow.get_or_create_metadata()
st.breadcrumb_item(
gui.breadcrumb_item(
metadata.short_title,
link_to=VideoBotsPage.app_url(),
className="text-muted",
)
if not (bi.published_run_id and bi.published_run.is_root()):
st.breadcrumb_item(
gui.breadcrumb_item(
run_title,
link_to=VideoBotsPage.app_url(**query_params),
className="text-muted",
)
st.breadcrumb_item(
gui.breadcrumb_item(
"Integrations",
link_to=VideoBotsPage.app_url(
**query_params,
Expand All @@ -170,8 +170,8 @@ def render_title_breadcrumb_share(
show_as_link=current_user and VideoBotsPage.is_user_admin(current_user),
)

with st.div(className="d-flex align-items-center"):
with st.div(className="d-flex align-items-start right-action-icons"):
with gui.div(className="d-flex align-items-center"):
with gui.div(className="d-flex align-items-start right-action-icons"):
copy_to_clipboard_button(
f'<i class="fa-regular fa-link"></i> <span class="d-none d-lg-inline"> Copy Link</span>',
value=current_url,
Expand All @@ -197,7 +197,7 @@ def _on_press_update(title: str, selected_graphs: list[dict]):
raise QueryParamsRedirectException(dict(title=title, graphs=graphs_json))


@st.cache_in_session_state
@gui.cache_in_session_state
def fetch_analysis_results(bi: BotIntegration) -> dict:
msgs = Message.objects.filter(
conversation__bot_integration=bi,
Expand All @@ -217,7 +217,7 @@ def fetch_analysis_results(bi: BotIntegration) -> dict:

def render_graph_data(bi: BotIntegration, results: dict, graph_data: dict):
key = graph_data["key"]
st.write(f"##### {key}")
gui.write(f"##### {key}")
obj_key = f"analysis_result__{key}"

if graph_data["data_selection"] == DataSelection.last.value:
Expand All @@ -227,7 +227,7 @@ def render_graph_data(bi: BotIntegration, results: dict, graph_data: dict):
.latest()
)
if not latest_msg:
st.write("No analysis results found")
gui.write("No analysis results found")
return
values = [[latest_msg.analysis_result.get(key), 1]]
elif graph_data["data_selection"] == DataSelection.convo_last.value:
Expand All @@ -249,7 +249,7 @@ def render_graph_data(bi: BotIntegration, results: dict, graph_data: dict):
for val in values:
if not val:
continue
st.write(val[0])
gui.write(val[0])
case GraphType.table_count.value:
render_table_count(values)
case GraphType.bar_count.value:
Expand All @@ -261,8 +261,8 @@ def render_graph_data(bi: BotIntegration, results: dict, graph_data: dict):


def render_table_count(values):
st.div(className="p-1")
st.data_table(
gui.div(className="p-1")
gui.data_table(
[["Value", "Count"]] + [[result[0], result[1]] for result in values],
)

Expand Down Expand Up @@ -318,4 +318,4 @@ def render_data_in_plotly(*data):
dragmode="pan",
),
)
st.plotly_chart(fig)
gui.plotly_chart(fig)
18 changes: 9 additions & 9 deletions daras_ai_v2/api_examples_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from furl import furl

import gooey_ui as st
import gooey_gui as gui
from auth.token_authentication import auth_keyword
from daras_ai_v2 import settings
from daras_ai_v2.doc_search_settings_widgets import is_user_uploaded_url
Expand All @@ -30,7 +30,7 @@ def get_filenames(request_body):
def api_example_generator(
*, api_url: furl, request_body: dict, as_form_data: bool, as_async: bool
):
js, python, curl = st.tabs(["`node.js`", "`python`", "`curl`"])
js, python, curl = gui.tabs(["`node.js`", "`python`", "`curl`"])

filenames = []
if as_async:
Expand Down Expand Up @@ -95,7 +95,7 @@ def api_example_generator(
json=shlex.quote(json.dumps(request_body, indent=2)),
)

st.write(
gui.write(
"""
1. Generate an api key [below👇](#api-keys)
Expand Down Expand Up @@ -193,7 +193,7 @@ def api_example_generator(
from black.mode import Mode

py_code = format_str(py_code, mode=Mode())
st.write(
gui.write(
rf"""
1. Generate an api key [below👇](#api-keys)
Expand Down Expand Up @@ -308,7 +308,7 @@ def api_example_generator(

js_code += "\n}\n\ngooeyAPI();"

st.write(
gui.write(
r"""
1. Generate an api key [below👇](#api-keys)
Expand Down Expand Up @@ -385,7 +385,7 @@ def bot_api_example_generator(integration_id: str):
integration_id=integration_id,
)

st.write(
gui.write(
f"""
Your Integration ID: `{integration_id}`
Expand All @@ -407,14 +407,14 @@ def bot_api_example_generator(integration_id: str):
)
/ "docs"
)
st.markdown(
gui.markdown(
f"""
Read our <a href="{api_docs_url}" target="_blank">complete API</a> for features like conversation history, input media files, and more.
""",
unsafe_allow_html=True,
)

st.js(
gui.js(
"""
document.startStreaming = async function() {
document.getElementById('stream-output').style.display = 'flex';
Expand All @@ -426,7 +426,7 @@ def bot_api_example_generator(integration_id: str):
).strip()
)

st.html(
gui.html(
f"""
<br>
<button class="btn btn-theme btn-secondary" onclick="document.startStreaming()">🏃‍♀️ Preview Streaming</button>
Expand Down
Loading

0 comments on commit b0c80da

Please sign in to comment.