haoyu commited on
Commit
ce5e147
β€’
1 Parent(s): 77cfef6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +163 -0
app.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ # from img_classification import teachable_machine_classification
3
+ # from PIL import Image, ImageOps
4
+ import streamlit_authenticator as stauth
5
+ import yaml
6
+ from yaml.loader import SafeLoader
7
+ import datetime
8
+ # import configparser
9
+ import webbrowser
10
+ import openai
11
+ from openai.error import InvalidRequestError
12
+ import requests
13
+ from diffusers import StableDiffusionPipeline
14
+ import torch
15
+ import io
16
+ from PIL import Image
17
+
18
+
19
+ # authentification
20
+ with open('./bla.yaml') as file:
21
+ config = yaml.load(file, Loader=SafeLoader)
22
+ authenticator = stauth.Authenticate(
23
+ config['credentials'],
24
+ config['cookie']['name'],
25
+ config['cookie']['key'],
26
+ config['cookie']['expiry_days'],
27
+ config['preauthorized']
28
+ )
29
+
30
+ name, authentication_status, username = authenticator.login('Login', 'main')
31
+ if authentication_status:
32
+ authenticator.logout('Logout', 'main')
33
+
34
+ # page = st.sidebar.selectbox("ζŽ’η΄’ζˆ–ι’„ζ΅‹", ("OpenJourney",
35
+ # "OpenAI_Dall-E",))
36
+
37
+ # if page == "OpenJourney":
38
+ st.title("使用 Huggingface ζ¨‘εž‹ η”Ÿζˆε›Ύεƒ")
39
+ st.write("model[link](https://huggingface.co/prompthero/openjourney?text=a+girl+sining+on+a+boat+on+the+river+in+a+forest)")
40
+
41
+ # model_id = "prompthero/openjourney"
42
+ # pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
43
+ # pipe = pipe.to("cuda")
44
+ # prompt = "retro serie of different cars with different colors and shapes, mdjrny-v4 style"
45
+ # image = pipe(prompt).images[0]
46
+ # image.save("./retro_cars.png")
47
+
48
+
49
+
50
+ prompt1 = st.text_input("Prompt", value="θΏ™ι‡ŒθΎ“ε…₯...")
51
+ # sizz = st.select_slider("倧小", options=(['1024x1024', '512x512', '256x256']))
52
+ sizz = st.radio(
53
+
54
+ "倧小",
55
+
56
+ ('prompthero/openjourney-v4','stabilityai/stable-diffusion-2-1','lambdalabs/sd-pokemon-diffusers','nitrosocke/Arcane-Diffusion','trinart_stable_diffusion_v2'))
57
+ # ("倧小", options=(['prompthero/openjourney-v4', 'stabilityai/stable-diffusion-2-1', 'lambdalabs/sd-pokemon-diffusers']))
58
+ st.write(sizz)
59
+ # st.write(sizz)
60
+ if st.button("η”Ÿζˆ"):
61
+ with st.spinner("η”Ÿζˆε›Ύεƒ..."):
62
+
63
+ API_URL = "https://api-inference.huggingface.co/models/"+sizz#prompthero/openjourney-v4"
64
+ headers = {"Authorization": f"Bearer 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"}
65
+
66
+ def query(payload):
67
+ response = requests.post(API_URL, headers=headers, json=payload)
68
+ return response.content
69
+ image_bytes = query({
70
+ "inputs": prompt1,
71
+ })
72
+ # print(image_bytes)
73
+ # You can access the image with PIL.Image for example
74
+
75
+ image = Image.open(io.BytesIO(image_bytes))
76
+ st.image(image)
77
+
78
+
79
+ # model_id = "prompthero/openjourney"
80
+ # pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
81
+ # pipe = pipe.to("cpu")
82
+ # prompt = prompt1
83
+ # image = pipe(prompt).images[0]
84
+ # st.image(image)
85
+ # image.save("./retro_cars.png")
86
+
87
+ # r = requests.post(
88
+ # "https://api.deepai.org/api/cute-creature-generator",
89
+ # data={
90
+ # 'text': prompt,
91
+ # },
92
+ # headers={'api-key': 'quickstart-QUdJIGlzIGNvbWluZy4uLi4K'}
93
+ # )
94
+ # print(r.json())
95
+ # st.write("图片网址[link]("+r.json()["output_url"]+")")
96
+
97
+ # elif page == "OpenAI_Dall-E":
98
+ # pass
99
+ # st.title("使用 DALL-E η”Ÿζˆε›Ύεƒ")
100
+ # st.write("教程[link](https://learndataanalysis.org/source-code-use-ai-to-create-images-with-python-tutorial-for-beginners-openai-dall-e-api/)")
101
+ # def generate_image(prompt, num_image=1, size='512x512', output_format='url'):
102
+ # """
103
+ # params:
104
+ # prompt (str):
105
+ # num_image (int):
106
+ # size (str):
107
+ # output_format (str):
108
+ # """
109
+ # try:
110
+ # images = []
111
+ # response = openai.Image.create(
112
+ # prompt=prompt,
113
+ # n=num_image,
114
+ # size=size,
115
+ # response_format=output_format
116
+ # )
117
+ # if output_format == 'url':
118
+ # for image in response['data']:
119
+ # images.append(image.url)
120
+ # elif output_format == 'b64_json':
121
+ # for image in response['data']:
122
+ # images.append(image.b64_json)
123
+ # return {'created': datetime.datetime.fromtimestamp(response['created']), 'images': images}
124
+ # except InvalidRequestError as e:
125
+ # print(e)
126
+
127
+ # # config = configparser.ConfigParser()
128
+ # # config.read('credential.ini')
129
+ # # API_KEY = config['openai']['APIKEY']
130
+ # openai.api_key = st.secrets["OPENAI_KEY"]
131
+
132
+ # SIZES = ('1024x1024', '512x512', '256x256')
133
+
134
+ # # generate images (url outputs)
135
+ # prompt = st.text_input("Prompt", value="θΏ™ι‡ŒθΎ“ε…₯...")
136
+ # sizz = st.select_slider("倧小", options=(['1024x1024', '512x512', '256x256']))
137
+ # # st.write(sizz)
138
+ # if st.button("η”Ÿζˆ"):
139
+ # with st.spinner("η”Ÿζˆε›Ύεƒ..."):
140
+ # response = generate_image(prompt, num_image=1, size=SIZES[0])
141
+ # response['created']
142
+ # images = response['images']
143
+ # for image in images:
144
+ # webbrowser.open(image)
145
+ # st.write("图片网址[link]("+image+")")
146
+
147
+ # ## generate images (byte output)
148
+ # # response = generate_image('San Francisco and Chicago mixed', num_image=2, size=SIZES[1], output_format='b64_json')
149
+ # # prefix = 'demo'
150
+ # # for indx, image in enumerate(response['images']):
151
+ # # with open(f'{prefix}_{indx}.jpg', 'wb') as f:
152
+ # # f.write(b64decode(image))
153
+
154
+
155
+
156
+
157
+
158
+
159
+ elif authentication_status == False:
160
+ st.error('Username/password is incorrect')
161
+ elif authentication_status == None:
162
+ st.warning('Please enter your username and password')
163
+