File size: 8,045 Bytes
6df42e3
fd1fd71
84e7abf
6df42e3
14051b6
6df42e3
14051b6
6df42e3
 
14051b6
 
 
6df42e3
14051b6
6df42e3
fd1fd71
6df42e3
fd1fd71
6df42e3
14051b6
6df42e3
 
 
 
 
14051b6
6df42e3
fd1fd71
6df42e3
14051b6
6df42e3
 
 
 
 
 
14051b6
6df42e3
 
 
14051b6
6df42e3
14051b6
 
 
6df42e3
 
 
 
14051b6
 
fd1fd71
6df42e3
14051b6
6df42e3
 
 
cdfff16
14051b6
 
cdfff16
14051b6
 
 
 
 
cdfff16
14051b6
 
fd1fd71
14051b6
fd1fd71
 
 
14051b6
 
 
cdfff16
14051b6
 
 
 
 
 
 
 
 
7f45073
 
fd1fd71
 
6df42e3
 
cdfff16
 
fd1fd71
cdfff16
 
d885278
cdfff16
 
6df42e3
 
cdfff16
 
 
 
6df42e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d885278
6df42e3
fd1fd71
6df42e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14051b6
6df42e3
 
14051b6
6df42e3
14051b6
6df42e3
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
from enkacard import encbanner
import asyncio
import os
import concurrent.futures

# from enkanetwork import EnkaNetworkAPI
from fastapi import FastAPI
from io import BytesIO
import enkanetwork
from fastapi.responses import (
    JSONResponse,
)  
import enkacard
import uvicorn
import requests

# client = EnkaNetworkAPI()

# import asyncio

# async def card():
#     print("cret")
#     async with encbanner.ENC(uid = "811455610") as encard:
#         print("creting")
#         return await encard.creat()

# result = asyncio.run(card()) 

# print(result)

# data_dir = "/tmp/data"
# if not os.path.exists(data_dir):
#     os.makedirs(data_dir)
# data_dir = "/tmp/langs"
# if not os.path.exists(data_dir):
#     os.makedirs(data_dir)

# async def main():
#     async with client:
#         await client.update_assets(lang = ["EN", "CHT"], path="/tmp")

# asyncio.run(main())

app = FastAPI()
# app = FastAPI(lifespan=lifespan)
async def card(id, designtype):
    async with encbanner.ENC(uid = str(id)) as encard:
        return await encard.creat(template = (2 if str(designtype) == "2" else 1))
    
@app.get("/{id}")  # Correct route definition without prefix
async def characters(id: int, design: str = "1"):  # Use async and await
    try:
        # characters = []
        result = await card(id, design)  # Use await instead of asyncio.run()
        print(result)
        characters = process_images(result)
        print(characters)

        # Return valid JSON response using FastAPI's JSONResponse
        return JSONResponse(content={'response': characters})

    except enkanetwork.exception.VaildateUIDError:
        return JSONResponse(content={'error': 'Invalid UID. Please check your UID.'}, status_code=400)

    except enkacard.enc_error.ENCardError:
        return JSONResponse(content={'error': 'Enable display of the showcase in the game or add characters there.'}, status_code=400)

    except Exception as e:
        return JSONResponse(content={'error': 'UNKNOWN ERR: ' + str(e)}, status_code=500)

@app.get("/")
def hello_world():
    return 'AMERICA YA HALLO!!'

# @app.route("/update_char")
# def upload():
    # data_dir = "/tmp/data"

    # if not os.path.exists(data_dir):
    #     os.makedirs(data_dir)

    # data_dir = "/tmp/langs"

    # if not os.path.exists(data_dir):
    #     os.makedirs(data_dir)
    # asyncio.run(update_genshin())
#     return 'Update smth ig!!'



def upload_image(data):
    print(data)
    url = "https://fighter-programmer-uploader.hf.space/upload"
    files = {'file': ('file', data, "image/png")}  
    response = requests.post(url, files=files)
    
    if response.status_code != 200:
        raise Exception(f"HTTP Error: {response.status_code}")
    
    try:
        body = response.json()
        if body["url"]:
            return body["url"]
        else:
            raise Exception(f"Telegraph error: {body.get('error', 'Unknown error')}")
    except (ValueError, KeyError, IndexError) as e:
        raise Exception(f"Failed to parse response: {str(e)}")
def process_image(dt):
    with BytesIO() as byte_io:
        dt.card.save(byte_io, "PNG")
        byte_io.seek(0)
        image_url = upload_image(byte_io)
        
        return {
            "name": dt.name,
            "url": image_url
        }

def process_images(result):
    characters = []
    with concurrent.futures.ThreadPoolExecutor() as executor:
        # Execute image uploads in parallel
        futures = [executor.submit(process_image, dt) for dt in result.card]
        
        for future in concurrent.futures.as_completed(futures):
            try:
                characters.append(future.result())
            except Exception as e:
                print(f"Error processing image: {e}")
    
    return characters
if __name__ == "__main__":
    # data_dir = "/tmp/data"

    # if not os.path.exists(data_dir):
    #     os.makedirs(data_dir)

    # data_dir = "/tmp/langs"

    # if not os.path.exists(data_dir):
    #     os.makedirs(data_dir)
    # asyncio.run(update_genshin())
    uvicorn.run("main:app", host="0.0.0.0", port=7860, workers=8, timeout_keep_alive=60000)
# import enkacard
# import enkacard.encbanner
# import enkanetwork
# import asyncio
# import requests
# from io import BytesIO
# from enkanetwork import EnkaNetworkAPI
# import os
# from contextlib import asynccontextmanager

# from fastapi import FastAPI

# from fastapi.responses import (
#     JSONResponse,
# )  
# from enkacard import enkatools

# import uvicorn

# enka_update = EnkaNetworkAPI()


# async def update_genshin():
#     try:
#         async with enka_update:
#             await enka_update.update_assets(path="/tmp", lang=["EN"])
    

#             # lang=["EN"], 
#             print("Finished update")
#     except Exception as e:
#         print(f"Update failed: {e}")

# async def card(id, designtype):
#     async with enkacard.encbanner.ENC(uid = str(id)) as encard:
#         return await encard.creat(template = (2 if str(designtype) == "2" else 1))
    
# @asynccontextmanager
# async def lifespan(app: FastAPI):
#     data_dir = "/tmp/data"

#     if not os.path.exists(data_dir):
#         os.makedirs(data_dir)

#     data_dir = "/tmp/langs"

#     if not os.path.exists(data_dir):
#         os.makedirs(data_dir)
#     await update_genshin()
#     yield
#     print("Goodbye")

# app = FastAPI()
# # app = FastAPI(lifespan=lifespan)

# @app.get("/{id}")  # Correct route definition without prefix
# async def characters(id: int, design: str = "1"):  # Use async and await
#     try:
#         characters = []
#         result = await card(id, design)  # Use await instead of asyncio.run()

#         for dt in result.card:
#             with BytesIO() as byte_io:
#                 dt.card.save(byte_io, "PNG")
#                 byte_io.seek(0)
#                 image_url = upload_image(byte_io)

#                 characters.append({
#                     "name": dt.name,
#                     "url": image_url
#                 })

#         # Return valid JSON response using FastAPI's JSONResponse
#         return JSONResponse(content={'response': characters})

#     except enkanetwork.exception.VaildateUIDError:
#         return JSONResponse(content={'error': 'Invalid UID. Please check your UID.'}, status_code=400)

#     except enkacard.enc_error.ENCardError:
#         return JSONResponse(content={'error': 'Enable display of the showcase in the game or add characters there.'}, status_code=400)

#     except Exception as e:
#         return JSONResponse(content={'error': 'UNKNOWN ERR: ' + str(e)}, status_code=500)

# @app.get("/")
# def hello_world():
#     return 'AMERICA YA HALLO!!'

# # @app.route("/update_char")
# # def upload():
#     # data_dir = "/tmp/data"

#     # if not os.path.exists(data_dir):
#     #     os.makedirs(data_dir)

#     # data_dir = "/tmp/langs"

#     # if not os.path.exists(data_dir):
#     #     os.makedirs(data_dir)
#     # asyncio.run(update_genshin())
# #     return 'Update smth ig!!'



# def upload_image(data):
#     url = "https://telegra.ph/upload"
#     files = {'file': ('file', data, "image/png")}  
#     response = requests.post(url, files=files)
    
#     if response.status_code != 200:
#         raise Exception(f"HTTP Error: {response.status_code}")
    
#     try:
#         body = response.json()
#         if isinstance(body, list) and 'src' in body[0]:
#             return "https://telegra.ph" + body[0]['src']
#         else:
#             raise Exception(f"Telegraph error: {body.get('error', 'Unknown error')}")
#     except (ValueError, KeyError, IndexError) as e:
#         raise Exception(f"Failed to parse response: {str(e)}")
    
# if __name__ == "__main__":
#     data_dir = "/tmp/data"

#     if not os.path.exists(data_dir):
#         os.makedirs(data_dir)

#     data_dir = "/tmp/langs"

#     if not os.path.exists(data_dir):
#         os.makedirs(data_dir)
#     asyncio.run(update_genshin())
#     uvicorn.run("main:app", host="0.0.0.0", port=7860, workers=8, timeout_keep_alive=600)