Skip to content

Commit

Permalink
update and clean up examples after FEPs 11 and 13
Browse files Browse the repository at this point in the history
  • Loading branch information
forrestbao committed Oct 27, 2023
1 parent a809092 commit baba606
Show file tree
Hide file tree
Showing 29 changed files with 353 additions and 303 deletions.
2 changes: 1 addition & 1 deletion docs
Submodule docs updated from 751ed1 to ba1613
8 changes: 2 additions & 6 deletions examples/AI/DallE.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,12 @@

@funix.funix( # Funix.io, the laziest way to build web apps in Python
title="OpenAI: Dall-E",
description="""Generate an image by prompt with DALL-E.""",
widgets={"openai_key": "password"},
description="""Generate an image by prompt with DALL-E. **Note:** An OpenAI key needs to be set in the environment variable OPENAI_KEY.""",
show_source=True,
)
def dalle(
Prompt: str = "a cat on a red jeep",
openai_key: str = "using environment variable",
Prompt: str = "a cat on a red jeep"
) -> IPython.display.Image:
if openai_key != "using environment variable":
openai.api_key = openai_key

response = openai.Image.create(prompt=Prompt)
return response["data"][0]["url"]
13 changes: 8 additions & 5 deletions examples/AI/chatGPT_advanced.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import os
import typing

import openai
import ipywidgets

import openai
openai.api_key = os.environ.get("OPENAI_KEY")

import funix


@funix.new_funix_type(
{
"name": "textarea",
Expand All @@ -21,17 +21,18 @@ class PromptBox(str):


cfg = { # declarative configuration, all in one place
"description": """Try the **ChatGPT** app in [Funix](http://funix.io)""",
"description": """Try the **ChatGPT** app in [Funix](http://funix.io). **Note: An OpenAI key needs to be set in the environment variable OPENAI_KEY.""",
"argument_labels": {
"prompt": "_What do you wanna ask?_",
"max_tokens": "**Length** of the answer",
"show_advanced": "Show advanced options",
"openai_key": "Use your own OpenAI key",
"model": "Choose a model",
},
"widgets": {"openai_key": "password", "model": "radio"},
"widgets": {"openai_key": "password"},
"conditional_visible": [
{"when": {"show_advanced": True}, "show": ["max_tokens", "model", "openai_key"]}
{"when": {"show_advanced": True},
"show": ["max_tokens", "model", "openai_key"]}
],
}

Expand All @@ -42,6 +43,8 @@ def ChatGPT_advanced(
show_advanced: bool = False,
model: typing.Literal["gpt-3.5-turbo", "gpt-3.5-turbo-0301"] = "gpt-3.5-turbo",
max_tokens: range(100, 500, 50) = 150,
# openai_key: ipywidgets.Password = "use environment variable",
# BUG: Conditional visible will not work if openai_key's type is ipywidgets.Password. Works if it's str.
openai_key: str = "use environment variable",
) -> str:
if openai_key != "use environment variable":
Expand Down
1 change: 0 additions & 1 deletion examples/AI/chatGPT_lazy.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Turn this function to a web app using the command:
# funix chatGPT_lazy.py -l # -l flag must be there.


import os # Python's native
import openai # you cannot skip it

Expand Down
4 changes: 3 additions & 1 deletion examples/AI/chatGPT_muilti_turn.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ def print_messages_html(messages):
return printout

import funix
@funix.funix(direction="column-reverse") # input is below log
@funix.funix(
description="""Multi-turn chat with ChatGPT. **Note:** An OpenAI key needs to be set in the environment variable OPENAI_KEY.""",
direction="column-reverse") # input is below log
def ChatGPT_multi_turn(current_message: str) -> IPython.display.HTML:
current_message = current_message.strip()
messages.append({"role": "user", "content": current_message})
Expand Down
5 changes: 5 additions & 0 deletions examples/AI/huggingface.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@

API_TOKEN = os.getenv("HF_TOKEN") # "Please set your API token as an environment variable named HF_TOKEN. You can get your token from https://huggingface.co/settings/token"

import funix

@funix.funix(
description="""Talk to LLMs hosted at HuggingFace. A HuggingFace token needs to be set in the environment variable HF_TOKEN.""",
)
def huggingface(
model_name: typing.Literal[
"gpt2",
Expand Down
12 changes: 3 additions & 9 deletions examples/AI/openAI_minimal_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,7 @@
import openai

import funix
from funix.session import get_global_variable, set_global_variable#, set_default_global_variable

# BUG: The set_global_variable() call does not effectively change the value of openai.api_key,
# though get_global_variable(openai.api_key) returns sessionized key value.
# The value of openai.api_key remains None unless set via the environment variable OPENAI_KEY.
# As a workaround, we use the POST method to demo.
from funix.session import get_global_variable, set_global_variable

# openai.api_key = os.environ.get("OPENAI_KEY")
openai_key = os.environ.get("OPENAI_KEY")
Expand All @@ -36,13 +31,12 @@ def set_openAI_key(api_key: str="", use_sys_env_var:bool=False) -> str:
return f"Your openAI key has been set to: {openai_key}"

# openai.api_key = api_key
set_global_variable(openai.api_key, api_key)
# set_global_variable(openai.api_key, api_key)
# FIXME: The two lines above are both useless to change openai.api_key. That's why we have to use POST method below to query all OpenAI endpoints. This is something to be fixed after grand opening.
return "OpenAI API key has been set via the web form! If it was set via an environment variable before, it's now overwritten."

@funix.funix()
def get_openAI_key()->str:
# return f"Your openAI key has been set to: {openai.api_key}"
# return f"Your openAI key has been set to: {get_global_variable(openai.api_key)}"
return f"Your openAI key has been set to: {openai_key}"

@funix.funix()
Expand Down
9 changes: 7 additions & 2 deletions examples/basic_usage/conditional_visibility.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
import typing

import ipywidgets

import funix

@funix.funix(
widgets={"prompt":"textarea", "model": "radio"},
widgets={"prompt":"textarea"},
conditional_visible=[
{
"when": {"show_advanced": True,},
"show": ["max_tokens", "model", "openai_key"]
}
]
)
def ChatGPT_advanced(prompt: str,
def conditional_visible(prompt: str,
show_advanced: bool = False,
model : typing.Literal['gpt-3.5-turbo', 'gpt-3.5-turbo-0301']= 'gpt-3.5-turbo',
max_tokens: range(100, 200, 20)=140,
# openai_key: ipywidgets.Password = "",) -> str:
# BUG: Reported elsewhere as well. If I replace the type to ipywidgets.Password, I will get an error at the frontend: Unsupported field schema for field root_openai_key: Unknown field type str.
openai_key: funix.hint.StrPassword = "",) -> str:


completion = openai.ChatCompletion.create(
messages=[{"role": "user", "content": prompt}],
model=model,
Expand Down
3 changes: 1 addition & 2 deletions examples/basic_usage/default_and_candidate_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@
import funix

@funix.funix(
title="Let users select",
description="This example shows how to provide argument/input values that users can select from in the UI. Simpliy taking advantage of Python's default values for keyword arguments, Literal type in type hints, and the `example` parameter in Funix. ",
examples={"arg3": [1, 5, 7]},
widgets={"arg2": "radio"},
show_source=True,
)
def argument_selection(
def default_and_candidate_values(
arg1: str = "prime",
arg2: typing.Literal["is", "is not"]="is",
arg3: int = 3,
Expand Down
1 change: 1 addition & 0 deletions examples/basic_usage/input_widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
# }
# )

@funix.funix()
def input_types(
prompt: str,
advanced_features: bool = False,
Expand Down
29 changes: 0 additions & 29 deletions examples/basic_usage/layout_simple.py

This file was deleted.

69 changes: 45 additions & 24 deletions examples/bioinformatics/tel_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import functools
import multiprocessing

import pandas, pandera

import funix

#%%
Expand Down Expand Up @@ -92,6 +94,8 @@ def search_telomeres(sRNAs:typing.List[str], repeat:str, include_reverse:bool=Tr
"""Determine whether a list of strings are telomers of the given repeat
"""

print (sRNAs)

telomere_hash_dict = get_telomere_hash_dict(repeat, include_reverse=include_reverse)

func_search_one_pattern = functools.partial(search_string_hash, telomere_hash_dict=telomere_hash_dict)
Expand All @@ -100,6 +104,8 @@ def search_telomeres(sRNAs:typing.List[str], repeat:str, include_reverse:bool=Tr
# result = pool.map(func_search_one_pattern, sRNAs)
result = list(map(func_search_one_pattern, sRNAs))

print (result )

return result

# %%
Expand All @@ -113,36 +119,51 @@ def test():
repeat = "CCCTAAA"

return search_telomeres(sRNAs, repeat)
# %%


class InputSchema(pandera.DataFrameModel):
sRNAs: pandera.typing.Series[str]


@funix.funix(
description = "A telomere is a region of repetitive DNA sequences at the end of a chromosome. "
"Find the belongings of a repeat unit.",
description = "A telomere is a region of repetitive DNA sequences at the end of a chromosome. Enter a repeating unit, and a list of sRNAs in the table below, this telomere checker will tell whether each of the sRNAs is a telomere.",
# destination = "column",
argument_config = {
"sRNAs": {
"widget" : "sheet"
},
"repeat_unit": {
# "treat_as": "config",
"examples": ["CCCTAAA"]
}
}
# argument_config = {
# "sRNAs": {
# "widget" : "sheet"
# },
# "repeat_unit": {
# # "treat_as": "config",
# "examples": ["CCCTAAA"]
# }
# }
)
def bioinfo_telomere_check(
sRNAs: typing.List[str]=
def telomere_check(
# sRNAs: typing.List[str] = [
# "CCCTAAACCCTAAACCCTAT", # False
# "CCCTAAACCCTAAACCCTAA", # True, 20-nt
# "CCCTAAACCCTAAACCC", # False, too short
# "CCCTAAACCCTAAACCCTAAAC", # True, 22-nt
# "CTAAACCCTAAACCCTAAACCCT" # True, 25-nt
# ],
sRNAs: pandera.typing.DataFrame[InputSchema] =
pandas.DataFrame({"sRNAs":
[
"CCCTAAACCCTAAACCCTAT", # False
"CCCTAAACCCTAAACCCTAA", # True, 20-nt
"CCCTAAACCCTAAACCC", # False, too short
"CCCTAAACCCTAAACCCTAAAC", # True, 22-nt
"CTAAACCCTAAACCCTAAACCCT" # True, 25-nt
]
, repeat_unit: str="CCCTAAA"
) -> dict:
"CCCTAAACCCTAAACCCTAT", # False
"CCCTAAACCCTAAACCCTAA", # True, 20-nt
"CCCTAAACCCTAAACCC", # False, too short
"CCCTAAACCCTAAACCCTAAAC", # True, 22-nt
"CTAAACCCTAAACCCTAAACCCT" # True, 25-nt
]
}),
repeat_unit: str="CCCTAAA"
# ) -> typing.Dict[str, bool]:
check_result = search_telomeres(sRNAs, repeat_unit)
return {"sRNAs":sRNAs, "Is it a telemere?":check_result }
# check_result = search_telomeres(sRNAs, repeat_unit)
# return {"sRNAs":sRNAs, "Is it a telemere?":check_result }

) -> pandas.DataFrame:
check_result = search_telomeres(sRNAs["sRNAs"].tolist(), repeat_unit)
return pandas.DataFrame({"sRNAs":sRNAs["sRNAs"], "Is it a telemere?":check_result })


if __name__ == '__main__':
Expand Down
Loading

0 comments on commit baba606

Please sign in to comment.