Skip to content

Commit be02aa4

Browse files
committed
Added new demo "Wikipedia assistant"
1 parent aa8ed4f commit be02aa4

File tree

15 files changed

+188
-159
lines changed

15 files changed

+188
-159
lines changed

python-web-io/.envrc.example.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# NOTE: save this file as .envrc and activate using `direnv allow` from same directory
22

3-
# if testing `tests/linux_gpt.py`, set your OpenAI API Key
3+
# if testing `examples/wikipedia_assistant.py`, set your OpenAI API Key
44
export OPENAI_API_KEY=""
55

66
# server env vars

python-web-io/.pythonwebio/config.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[script]
2-
filepath = "examples/color_names.py"
2+
filepath = "examples/wikipedia_assistant.py"
33
entrypoint = "main"
44

55
[page]

python-web-io/Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ install: ## install dependencies
66

77
publish: ## build module and publish as new version to PyPI
88
@poetry build
9-
@poetry publish
9+
@poetry publish --username=$(PYPI_USERNAME) --password=$(PYPI_PASSWORD)
1010

1111
help: ## display this help screen
1212
@grep -h -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'

python-web-io/README.md

Lines changed: 43 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,60 @@
1-
# Python Web I/O
1+
# <img src="./.github/logo.png" style="width:40px;padding-right:10px;margin-bottom:-8px;" alt="Sticker of a cute yellow Python snake, representing the use of the Python programming language in this project."> Python Web I/O
22
Generate a webpage as a GUI for a Python script, and serve from anywhere.
33

4-
## Usage
5-
```
6-
$ export SECRET_KEY="someSecureSecretKey"
7-
$ python_web_io .\example.py
8-
```
9-
* Create a `.envrc` file, setting `SECRET_KEY` as per [`python_web_io/.envrc.example`](https://github.com/Cutwell/python-web-io/blob/main/python_web_io/.envrc.example).
10-
* Try running the [`example.py`](https://github.com/Cutwell/python-web-io/blob/main/python_web_io/example.py) script using `python_web_io example.py`.
4+
## Documentation
5+
Check out the [wiki](https://github.com/Cutwell/python-web-io/wiki).
116

12-
|Argument|||
13-
|:---:|:---:|:---:|
14-
|`"example.py"`|Required|Specify the file path for the app Python script / entrypoint.|
15-
|`--debug`|Optional|Run the Flask server with debug output enabled.|
7+
## Quickstart
168

17-
## Config
18-
### Magic
19-
`input()` and `print()` both support the `magic` keyword argument. For `input()`, `magic` sets the `type` of the input html element. For `print()`, `magic` sets the element type.
9+
Install `python-web-io` locally using:
10+
```bash
11+
pip install python-web-io
12+
```
2013

21-
||Magic|Default|
22-
|:---:|:---:|:---:|
23-
|`input()`|`button`, `checkbox`, `color`, `date`, `datetime-local`, `email`, `file`, `image`, `month`, `number`, `password`, `radio`, `range`, `search`, `tel`, `text`, `time`, `url`, `week`|`text`|
24-
|`print()`|`style`, `img`, `address`, `footer`, `aside`, `header`, `h1..6`, `blockquote`, `p`, `b`, `abbr`, `code`, `em`, `i`, `mark`, `q`, `s`, `small`, `span`, `strong`, |`p`|
14+
Or via `poetry` using:
15+
```bash
16+
poetry add python_web_io
17+
```
2518

26-
#### Arguments
27-
`input()` and `print()` both support the `magic_args` keyword argument. `magic_args` accepts a dictionary, which can be used to set attributes for the html element.
19+
If evaluating / testing `python-web-io`, install dependencies for the example apps using:
20+
```bash
21+
poetry add python_web_io --with examples
22+
```
2823

29-
### Cache
30-
The user script is re-evaluated after each user interaction, to progress the script to the next `input()`, etc. This means expensive functions may be called more than once per session. To reduce latency, a cache decorator is made available through the `python_web_io` module. The `@cache_to_file()` decorator accepts a single argument: `file_path`, which indicates where the cache (a `.pkl` file) should be stored.
24+
After installing the project, some environment setup is required:
3125

32-
```python3
33-
import python_web_io as io
26+
### Required setup
27+
Create an `app.py` file containing your script, and an `.envrc` file to store project secrets. (Note: remember to add `.envrc` to your `.gitignore`)
28+
Look for example apps in [`./python_web_io/examples`](https://github.com/Cutwell/python-web-io/tree/main/python_web_io/examples).
29+
```
30+
.
31+
├── .envrc
32+
├── config.toml
33+
└── app.py
34+
```
3435

35-
@io.cache_to_file('cache.pickle')
36-
def expensive_function(arg):
37-
# Calculate the result here
38-
return result
36+
Add the following environment variables to your `.envrc`. (Note: remember to activate the `.envrc` in your terminal using `direnv allow`)
37+
```bash
38+
# server env vars
39+
export PYTHON_WEB_IO_SECRET=""
40+
export PYTHON_WEB_IO_CONFIG=".pythonwebio/config.toml" # defaults to .pythonwebio/config.toml if not set
3941
```
4042

41-
Cache is persistent across sessions, allowing multiple users to access it. Session specific data can be stored using `session` from `flask`.
43+
Generate a random key for `PYTHON_WEB_IO_SECRET` using this python command line snippet:
44+
```bash
45+
python -c 'import secrets; print(secrets.token_hex())'
46+
```
4247

43-
```python3
44-
from flask import session
45-
session['some_var] = 'some_val'
48+
If testing `wikipedia_assistant.py`, an OpenAI API key will also need to be set.
49+
```bash
50+
export OPENAI_API_KEY=""
4651
```
4752

48-
Reserved keys for the `session` namespace are: `io` and `counter`.
53+
### Running the webapp
54+
We recommend running `python_web_io` using `uvicorn`:
55+
```bash
56+
poetry run uvicorn python_web_io.main:app
57+
```
4958

5059
## License
5160
MIT

python-web-io/examples/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ Download the free [World Cities Database](https://simplemaps.com/data/world-citi
2020
Demo of LangChain integration, using an OpenAI LLM to imitate a linux terminal.
2121

2222
```bash
23-
poetry run python_web_io --config=examples/linux_gpt.toml
23+
poetry run python_web_io --config=examples/wikipedia_assistant.toml
2424
```
2525

2626
## 🎨 Color names

python-web-io/examples/color_names.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,6 @@ def main():
7272

7373
hex_color = input("What's your favourite color?", type="color")
7474
print(f"Nice! That colour looks like {get_nearest_color_name(hex_color)}!")
75+
76+
if __name__ == "__main__":
77+
main()

python-web-io/examples/linux_gpt.py

Lines changed: 0 additions & 47 deletions
This file was deleted.

python-web-io/examples/weather_app.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,4 +198,7 @@ def main():
198198
f"Last updated ↻: {day_of_week}, {date_time_str}<br>",
199199
f"Temperature 🌡️: {weather['current_weather']['temperature']}°C<br>",
200200
f"Wind speed 💨: {weather['current_weather']['windspeed']} km/h, Wind direction 🧭: {winddirection}° ({degrees_to_direction(winddirection)})"
201-
)
201+
)
202+
203+
if __name__ == "__main__":
204+
main()
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import openai
2+
import python_web_io as io
3+
4+
template = "I want you to act like a wikipedia expert. You have knowledge of every topic that exists on wikipedia, and can accurately give information about any query. When answering questions, provide links to every wikipedia page referenced. Format all links using markdown formatting. Do not complete the previous input, generate a new response as its own paragraph."
5+
6+
chat_history = [
7+
template
8+
]
9+
10+
# cache prompt + responses so the conversation being replayed up to N steps doesn't require N API calls.
11+
@io.cache_to_file("cache.pickle")
12+
def chat_with_model(prompt):
13+
chat_history.append(prompt)
14+
response = openai.Completion.create(
15+
engine="text-davinci-003",
16+
prompt=" ".join(chat_history),
17+
max_tokens=1024, # Adjust as needed
18+
n=1,
19+
stop=None,
20+
temperature=0.5,
21+
)
22+
return response.choices[0].text.strip()
23+
24+
def main():
25+
print("<h2>Wikipedia Assistant</h2>")
26+
27+
print("Chat with the OpenAI model (type 'exit' to quit)")
28+
29+
print("<small>System prompt:", template, "</small>")
30+
31+
while True:
32+
print("<br>")
33+
user_input = input("👩‍💻 You: ")
34+
if user_input.lower() == 'exit':
35+
print("🤖: Goodbye!")
36+
break
37+
38+
response = chat_with_model(user_input)
39+
print(f"🤖: {response}")
40+
41+
if __name__ == "__main__":
42+
main()

python-web-io/examples/linux_gpt.toml renamed to python-web-io/examples/wikipedia_assistant.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[script]
2-
filepath = "examples/linux_gpt.py"
2+
filepath = "examples/wikipedia_assistant.py"
33
entrypoint = "main"
44

55
[page]

0 commit comments

Comments
 (0)