Spaces:
Sleeping
Sleeping
Gastby
commited on
Commit
•
c14816f
1
Parent(s):
bdecf34
Add application file
Browse files- Dockerfile +14 -0
- api_module.py +121 -0
- main.py +193 -0
- requirements.txt +10 -0
Dockerfile
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# read the doc: https://huggingface.co/docs/hub/spaces-sdks-docker
|
2 |
+
# you will also find guides on how best to write your Dockerfile
|
3 |
+
|
4 |
+
FROM python:3.9
|
5 |
+
|
6 |
+
WORKDIR /code
|
7 |
+
|
8 |
+
COPY ./requirements.txt /code/requirements.txt
|
9 |
+
|
10 |
+
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
11 |
+
|
12 |
+
COPY . .
|
13 |
+
|
14 |
+
CMD ["uvicorn", "app.main:api --reload", "--host", "0.0.0.0", "--port", "7860"]
|
api_module.py
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
import time
|
3 |
+
|
4 |
+
|
5 |
+
def make_imagine_request(api_key, prompt):
|
6 |
+
endpoint = "https://api.midjourneyapi.xyz/mj/v2/imagine"
|
7 |
+
headers = {
|
8 |
+
'X-API-KEY': api_key,
|
9 |
+
'Content-Type': 'application/json',
|
10 |
+
}
|
11 |
+
payload = {
|
12 |
+
"prompt": prompt.strip(),
|
13 |
+
"process_mode": "fast"
|
14 |
+
}
|
15 |
+
response = requests.post(endpoint, headers=headers, json=payload).json()
|
16 |
+
# check if api key is valid
|
17 |
+
if "message" in response and response["message"] == "Invalid API key":
|
18 |
+
print('Invalid API key')
|
19 |
+
return None
|
20 |
+
# check if api key has enough credits
|
21 |
+
if "message" in response and response["message"] == "Insufficient token":
|
22 |
+
print('Insufficient token')
|
23 |
+
return None
|
24 |
+
|
25 |
+
task_id = response.get("task_id", None)
|
26 |
+
if task_id is not None:
|
27 |
+
print(f'Task id for prompt \'{prompt}\': {task_id}')
|
28 |
+
else:
|
29 |
+
print('Failed to get task id')
|
30 |
+
|
31 |
+
return task_id
|
32 |
+
|
33 |
+
def make_upscale_request(api_key, original_task_id, index):
|
34 |
+
endpoint = "https://api.midjourneyapi.xyz/mj/v2/upscale"
|
35 |
+
headers = {
|
36 |
+
'X-API-KEY': api_key,
|
37 |
+
'Content-Type': 'application/json',
|
38 |
+
}
|
39 |
+
payload = {
|
40 |
+
"origin_task_id": original_task_id,
|
41 |
+
"index": str(index)
|
42 |
+
}
|
43 |
+
response = requests.post(endpoint, headers=headers, json=payload).json()
|
44 |
+
task_id = response.get("task_id", None)
|
45 |
+
if task_id is not None:
|
46 |
+
print(f'Upscale Task id for prompt: {task_id}')
|
47 |
+
else:
|
48 |
+
print('Failed to get task id')
|
49 |
+
|
50 |
+
return task_id
|
51 |
+
|
52 |
+
def make_outpaint_request(api_key, prompt, original_task_id):
|
53 |
+
endpoint = "https://api.midjourneyapi.xyz/mj/v2/outpaint"
|
54 |
+
headers = {
|
55 |
+
'X-API-KEY': api_key,
|
56 |
+
'Content-Type': 'application/json',
|
57 |
+
}
|
58 |
+
payload = {
|
59 |
+
"origin_task_id": original_task_id,
|
60 |
+
"zoom_ratio": "2",
|
61 |
+
"prompt": prompt.strip(),
|
62 |
+
}
|
63 |
+
response = requests.post(endpoint, headers=headers, json=payload).json()
|
64 |
+
task_id = response.get("task_id", None)
|
65 |
+
if task_id is not None:
|
66 |
+
print(f'Task id for prompt \'{prompt}\': {task_id}')
|
67 |
+
else:
|
68 |
+
print('Failed to get task id')
|
69 |
+
|
70 |
+
return task_id
|
71 |
+
|
72 |
+
def make_vary_request(api_key, prompt, original_task_id):
|
73 |
+
endpoint = "https://api.midjourneyapi.xyz/mj/v2/variation"
|
74 |
+
headers = {
|
75 |
+
'X-API-KEY': api_key,
|
76 |
+
'Content-Type': 'application/json',
|
77 |
+
}
|
78 |
+
payload = {
|
79 |
+
"origin_task_id": original_task_id,
|
80 |
+
'index': 'high_variation',
|
81 |
+
'prompt': prompt,
|
82 |
+
'aspect_ratio': '1:1'
|
83 |
+
}
|
84 |
+
response = requests.post(endpoint, headers=headers, json=payload).json()
|
85 |
+
task_id = response.get("task_id", None)
|
86 |
+
if task_id is not None:
|
87 |
+
print(f'Task id for prompt \'{prompt}\': {task_id}')
|
88 |
+
else:
|
89 |
+
print('Failed to get task id')
|
90 |
+
|
91 |
+
return task_id
|
92 |
+
|
93 |
+
def fetch_request(api_key, task_id, max_retries=35):
|
94 |
+
endpoint = "https://api.midjourneyapi.xyz/mj/v2/fetch"
|
95 |
+
headers = {
|
96 |
+
'X-API-KEY': api_key
|
97 |
+
}
|
98 |
+
payload = {
|
99 |
+
"task_id": task_id
|
100 |
+
}
|
101 |
+
|
102 |
+
retries = 0
|
103 |
+
while True:
|
104 |
+
response = requests.post(endpoint, headers=headers, json=payload)
|
105 |
+
if response.status_code == 200:
|
106 |
+
response_json = response.json()
|
107 |
+
status = response_json.get('status', '')
|
108 |
+
if status == 'finished':
|
109 |
+
discord_url = response_json['task_result'].get('discord_image_url', '')
|
110 |
+
return discord_url
|
111 |
+
elif status == 'failed':
|
112 |
+
print('Task failed. Stopping retrieval attempts.')
|
113 |
+
return None
|
114 |
+
else:
|
115 |
+
print('Result not ready yet, retrying in 10 seconds...')
|
116 |
+
else:
|
117 |
+
print('Failed to fetch result, retrying in 10 seconds...')
|
118 |
+
retries += 1
|
119 |
+
if retries > max_retries:
|
120 |
+
raise Exception('Failed to fetch result after maximum retries.')
|
121 |
+
time.sleep(10)
|
main.py
ADDED
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException
|
2 |
+
from pydantic import BaseModel
|
3 |
+
from typing import Optional
|
4 |
+
import api_module as mj
|
5 |
+
import random
|
6 |
+
from io import BytesIO
|
7 |
+
import openai
|
8 |
+
from transparent_background import Remover
|
9 |
+
import requests
|
10 |
+
from PIL import Image
|
11 |
+
from qiniu import Auth, put_data, etag, Zone
|
12 |
+
import replicate
|
13 |
+
|
14 |
+
|
15 |
+
mj_api_key = '3bb41ebb-5e2f-44be-bf10-2774b9e2c85a'
|
16 |
+
openai.api_key = 's'
|
17 |
+
access_key = 'Xq74_ChGkY0ZXTmwhH2FkthFD6SYzfFXQ5YIECJk'
|
18 |
+
secret_key = 'z735vaPllNa7E46dwlZhl18RbI9PLNuakPt_dfdA'
|
19 |
+
bucket_name = 'mystory-games'
|
20 |
+
|
21 |
+
|
22 |
+
|
23 |
+
def translate_to_english(text):
|
24 |
+
response = openai.ChatCompletion.create(
|
25 |
+
model="gpt-4",
|
26 |
+
messages=[
|
27 |
+
{
|
28 |
+
"role": "system",
|
29 |
+
"content": "accurately translating Chinese text to English, while keeping the context and idiomatically correct in English, ensure that only translated content is replied to \n"
|
30 |
+
},
|
31 |
+
{
|
32 |
+
"role": "user",
|
33 |
+
"content": text
|
34 |
+
},
|
35 |
+
],
|
36 |
+
temperature=0.2,
|
37 |
+
max_tokens=256,
|
38 |
+
top_p=1,
|
39 |
+
frequency_penalty=0,
|
40 |
+
presence_penalty=0
|
41 |
+
)
|
42 |
+
|
43 |
+
translated_text = response['choices'][0]['message']['content'].strip()
|
44 |
+
return translated_text
|
45 |
+
|
46 |
+
def translate_to_chinese(text):
|
47 |
+
response = openai.ChatCompletion.create(
|
48 |
+
model="gpt-4",
|
49 |
+
messages=[
|
50 |
+
{
|
51 |
+
"role": "system",
|
52 |
+
"content": "accurately translating English text to Chinese, while keeping the context and idiomatically correct in Chinese, ensure that only translated content is replied to \n"
|
53 |
+
},
|
54 |
+
{
|
55 |
+
"role": "user",
|
56 |
+
"content": text
|
57 |
+
},
|
58 |
+
],
|
59 |
+
temperature=0.2,
|
60 |
+
max_tokens=256,
|
61 |
+
top_p=1,
|
62 |
+
frequency_penalty=0,
|
63 |
+
presence_penalty=0
|
64 |
+
)
|
65 |
+
|
66 |
+
translated_text = response['choices'][0]['message']['content'].strip()
|
67 |
+
return translated_text
|
68 |
+
|
69 |
+
def avatar_create(text):
|
70 |
+
#translate to english
|
71 |
+
text = translate_to_english(text)
|
72 |
+
#add text to prompt
|
73 |
+
prompt = f'{text}, concept art by Pixar, cgsociety, character, furry art, full body shot, white background, Realistic 3d render --v 5.2'
|
74 |
+
#make imagine request
|
75 |
+
max_retries = 5
|
76 |
+
retries = 0
|
77 |
+
while retries < max_retries:
|
78 |
+
task_id = mj.make_imagine_request(mj_api_key, prompt)
|
79 |
+
if task_id is not None:
|
80 |
+
break
|
81 |
+
else:
|
82 |
+
retries += 1
|
83 |
+
print(f'Failed to get task id, retrying {retries}/{max_retries}...')
|
84 |
+
if retries == max_retries:
|
85 |
+
print('Failed to get task id, aborting')
|
86 |
+
return None
|
87 |
+
|
88 |
+
#fetch request
|
89 |
+
# make sure the imagine process has finished
|
90 |
+
while True:
|
91 |
+
image_url = mj.fetch_request(mj_api_key, task_id)
|
92 |
+
if image_url is not None:
|
93 |
+
break
|
94 |
+
elif image_url is None:
|
95 |
+
print('Imagine process failed, exiting...')
|
96 |
+
raise SystemExit('Imagine process failed')
|
97 |
+
return task_id
|
98 |
+
|
99 |
+
def avatar_remove_background(image_url):
|
100 |
+
remover = Remover() # default settings
|
101 |
+
# downlaod image
|
102 |
+
response = requests.get(image_url)
|
103 |
+
# convert to PIL image
|
104 |
+
img = Image.open(BytesIO(response.content)).convert('RGB')
|
105 |
+
# remove background
|
106 |
+
out = remover.process(img, type='rgba')
|
107 |
+
image_io = BytesIO()
|
108 |
+
Image.fromarray(out).save(image_io, format='PNG')
|
109 |
+
image_data = image_io.getvalue()
|
110 |
+
|
111 |
+
# Upload the image data
|
112 |
+
q = Auth(access_key, secret_key)
|
113 |
+
token = q.upload_token(bucket_name)
|
114 |
+
ret, info = put_data(token, None, image_data, mime_type="image/png")
|
115 |
+
if info.status_code == 200:
|
116 |
+
cdn_url = 'http://image1.juramaia.com/' + ret['key']
|
117 |
+
return cdn_url
|
118 |
+
else:
|
119 |
+
print('Failed to upload image to CDN')
|
120 |
+
return None
|
121 |
+
|
122 |
+
def avatar_upscale(task_id, index):
|
123 |
+
task_id = mj.make_upscale_request(mj_api_key, task_id, index)
|
124 |
+
# make sure the upscale task sucessfully
|
125 |
+
if task_id is not None:
|
126 |
+
pass
|
127 |
+
elif task_id is None:
|
128 |
+
print('Upscale process failed, exiting...')
|
129 |
+
raise SystemExit('Upscale process failed')
|
130 |
+
# make sure the upscale process has finished
|
131 |
+
while True:
|
132 |
+
upscale_image_url = mj.fetch_request(mj_api_key, task_id)
|
133 |
+
if upscale_image_url is not None:
|
134 |
+
break
|
135 |
+
elif upscale_image_url is None:
|
136 |
+
print('Upscale process failed, exiting...')
|
137 |
+
raise SystemExit('Upscale process failed')
|
138 |
+
return upscale_image_url
|
139 |
+
|
140 |
+
def main_process(text):
|
141 |
+
#create avatar
|
142 |
+
task_id = avatar_create(text)
|
143 |
+
print(f'\navatar create successful task_id is {task_id}\n')
|
144 |
+
#upscale avatar and remove background
|
145 |
+
index = random.randint(1, 4)
|
146 |
+
while True:
|
147 |
+
print(f'upsclae index is {index} and task_id is {task_id}')
|
148 |
+
upscale_image_url = avatar_upscale(task_id, index)
|
149 |
+
if upscale_image_url is not None:
|
150 |
+
break
|
151 |
+
elif upscale_image_url is None:
|
152 |
+
print('Upscale process failed, exiting...')
|
153 |
+
raise SystemExit('Upscale process failed')
|
154 |
+
print(f'upscale_image_url is {upscale_image_url}')
|
155 |
+
return upscale_image_url
|
156 |
+
|
157 |
+
def analyze_process(url):
|
158 |
+
print(f'\nanalyzing image: {url}')
|
159 |
+
eng_output = replicate.run(
|
160 |
+
"andreasjansson/blip-2:4b32258c42e9efd4288bb9910bc532a69727f9acd26aa08e175713a0a857a608",
|
161 |
+
input={
|
162 |
+
"image": url,
|
163 |
+
"caption": True,
|
164 |
+
"temperature": 0.5
|
165 |
+
}
|
166 |
+
)
|
167 |
+
output = translate_to_chinese(eng_output)
|
168 |
+
print(f'analyzed caption: {output}\n')
|
169 |
+
return output
|
170 |
+
|
171 |
+
|
172 |
+
class Item(BaseModel):
|
173 |
+
text: str
|
174 |
+
|
175 |
+
api = FastAPI()
|
176 |
+
|
177 |
+
@api.post("/main_process/")
|
178 |
+
async def main_api(item: Item):
|
179 |
+
try:
|
180 |
+
image_url = main_process(item.text)
|
181 |
+
return {"image_url": image_url}
|
182 |
+
except Exception as e:
|
183 |
+
raise HTTPException(status_code=400, detail=str(e))
|
184 |
+
|
185 |
+
@api.post("/analyze_process/")
|
186 |
+
async def analyze_api(item: Item):
|
187 |
+
try:
|
188 |
+
output = analyze_process(item.text)
|
189 |
+
return {"output": output}
|
190 |
+
except Exception as e:
|
191 |
+
raise HTTPException(status_code=400, detail=str(e))
|
192 |
+
|
193 |
+
|
requirements.txt
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
numpy
|
2 |
+
qiniu
|
3 |
+
requests
|
4 |
+
openai
|
5 |
+
pillow
|
6 |
+
transparent_background
|
7 |
+
replicate
|
8 |
+
fastapi
|
9 |
+
pydantic
|
10 |
+
uvicorn
|