Skip to content

Commit

Permalink
Merge pull request #1941 from jereanon/fix/25-examples-repo
Browse files Browse the repository at this point in the history
Address discrepancies between examples repo and examples
  • Loading branch information
jkelleyrtp authored Feb 16, 2024
2 parents 6cd9c69 + b7cc743 commit a454f2c
Show file tree
Hide file tree
Showing 4 changed files with 417 additions and 28 deletions.
8 changes: 8 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -172,3 +172,11 @@ required-features = ["http"]
[[example]]
name = "suspense"
required-features = ["http"]

[[example]]
name = "weather_app"
required-features = ["http"]

[[example]]
name = "image_generator_openai"
required-features = ["http"]
28 changes: 0 additions & 28 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,10 @@ cargo run --example hello_world

### Props

[borrowed](./borrowed.rs) - Borrowed props

[inlineprops](./inlineprops.rs) - Demo of `inline_props` macro

[optional_props](./optional_props.rs) - Optional props

### CSS

[all_css](./all_css.rs) - You can specify any CSS attribute

[tailwind](./tailwind/) - You can use a library for styling

## Input Handling
Expand All @@ -58,12 +52,6 @@ cargo run --example hello_world

### State Management

[fermi](./fermi.rs) - Fermi library for state management

[pattern_reducer](./pattern_reducer.rs) - The reducer pattern with `use_state`

[rsx_compile_fail](./rsx_compile_fail.rs)

### Async

[login_form](./login_form.rs) - Login endpoint example
Expand All @@ -74,22 +62,8 @@ cargo run --example hello_world

### SVG

[svg_basic](./svg_basic.rs)

[svg](./svg.rs)

### Performance

[framework_benchmark](./framework_benchmark.rs) - Renders a huge list

> Note: The benchmark should be run in release mode:
>
>```shell
> cargo run --example framework_benchmark --release
>```
[heavy_compute](./heavy_compute.rs) - How to deal with expensive operations
## Server-side rendering

[ssr](./ssr.rs) - Rendering RSX server-side
Expand Down Expand Up @@ -120,8 +94,6 @@ cargo run --example hello_world

[calculator](./calculator.rs) - Simple calculator

[pattern_model](./pattern_model.rs) - Simple calculator, but using a custom struct as the model
[crm](./crm.rs) - Toy multi-page customer management app

[dog_app](./dog_app.rs) - Accesses dog API
Expand Down
150 changes: 150 additions & 0 deletions examples/image_generator_openai.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
use dioxus::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::{json, Error};

fn main() {
launch(app)
}

fn app() -> Element {
let mut api = use_signal(|| "".to_string());
let mut prompt = use_signal(|| "".to_string());
let mut n_image = use_signal(|| 1.to_string());
let mut image = use_signal(|| ImageResponse {
created: 0,
data: Vec::new(),
});
let mut loading = use_signal(|| "".to_string());

let mut generate_images = use_resource(move || async move {
let api_key = api.peek().clone();
let prompt = prompt.peek().clone();
let number_of_images = n_image.peek().clone();

if (api_key.is_empty() || prompt.is_empty() || number_of_images.is_empty()) {
return;
}

loading.set("is-loading".to_string());
let images = request(api_key, prompt, number_of_images).await;
match images {
Ok(imgz) => {
image.set(imgz);
}
Err(e) => {
println!("Error: {:?}", e);
}
}
loading.set("".to_string());
});

rsx! {
head {
link {
rel: "stylesheet",
href: "https://unpkg.com/[email protected]/css/bulma.min.css",
}
}
div { class: "container",
div { class: "columns",
div { class: "column",
input { class: "input is-primary mt-4",
value:"{api}",
r#type: "text",
placeholder: "API",
oninput: move |evt| {
api.set(evt.value().clone());
},
}

input { class: "input is-primary mt-4",
placeholder: "MAX 1000 Dgts",
r#type: "text",
value:"{prompt}",
oninput: move |evt| {
prompt.set(evt.value().clone());
},
}

input { class: "input is-primary mt-4",
r#type: "number",
min:"1",
max:"10",
value:"{n_image}",
oninput: move |evt| {
n_image.set(evt.value().clone());
},
}
}
}

button { class: "button is-primary {loading}",
onclick: move |_| {
generate_images.restart();
},
"Generate image"
}
br {
}
}
{image.read().data.iter().map(|image| {
rsx!(
section { class: "is-flex",
div { class: "container is-fluid",
div { class: "container has-text-centered",
div { class: "is-justify-content-center",
div { class: "level",
div { class: "level-item",
figure { class: "image",
img {
alt: "",
src: "{image.url}",
}
}
}
}
}
}
}
}
)
})
} }
}
async fn request(api: String, prompt: String, n_image: String) -> Result<ImageResponse, Error> {
let client = reqwest::Client::new();
let body = json!({
"prompt": prompt,
"n":n_image.parse::<i32>().unwrap_or(1),
"size":"1024x1024",
});

let mut authorization = "Bearer ".to_string();
authorization.push_str(&api);

let res = client
.post("https://api.openai.com/v1/images/generations")
.body(body.to_string())
.header("Content-Type", "application/json")
.header("Authorization", authorization)
.send()
.await
.unwrap()
.text()
.await
.unwrap();

let deserialized: ImageResponse = serde_json::from_str(&res)?;
Ok(deserialized)
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Props, Clone)]
struct UrlImage {
url: String,
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Props, Clone)]
struct ImageResponse {
created: i32,
data: Vec<UrlImage>,
}
Loading

0 comments on commit a454f2c

Please sign in to comment.