cINAWGD commited on
Commit
a439dad
·
verified ·
1 Parent(s): c9e2c2f

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +75 -267
main.py CHANGED
@@ -1,276 +1,84 @@
1
- from enkacard import encbanner
2
- import asyncio
3
  import os
4
- import concurrent.futures
5
-
6
- # from enkanetwork import EnkaNetworkAPI
7
- from fastapi import FastAPI
8
- from io import BytesIO
9
- import enkanetwork
10
- from fastapi.responses import (
11
- JSONResponse,
12
- )
13
- import enkacard
14
- import uvicorn
15
- import requests
16
-
17
- # client = EnkaNetworkAPI()
18
-
19
- # import asyncio
20
-
21
- # async def card():
22
- # print("cret")
23
- # async with encbanner.ENC(uid = "811455610") as encard:
24
- # print("creting")
25
- # return await encard.creat()
26
-
27
- # result = asyncio.run(card())
28
-
29
- # print(result)
30
-
31
- # data_dir = "/tmp/data"
32
- # if not os.path.exists(data_dir):
33
- # os.makedirs(data_dir)
34
- # data_dir = "/tmp/langs"
35
- # if not os.path.exists(data_dir):
36
- # os.makedirs(data_dir)
37
-
38
- # async def main():
39
- # async with client:
40
- # await client.update_assets(lang = ["EN", "CHT"], path="/tmp")
41
-
42
- # asyncio.run(main())
43
-
44
- app = FastAPI()
45
- # app = FastAPI(lifespan=lifespan)
46
- async def card(id, designtype):
47
- async with encbanner.ENC(uid = str(id)) as encard:
48
- return await encard.creat(template = (2 if str(designtype) == "2" else 1))
49
 
50
- @app.get("/{id}") # Correct route definition without prefix
51
- async def characters(id: int, design: str = "1"): # Use async and await
 
 
52
  try:
53
- # characters = []
54
- result = await card(id, design) # Use await instead of asyncio.run()
55
- print(result)
56
- characters = process_images(result)
57
- print(characters)
58
-
59
- # Return valid JSON response using FastAPI's JSONResponse
60
- return JSONResponse(content={'response': characters})
61
-
62
- except enkanetwork.exception.VaildateUIDError:
63
- return JSONResponse(content={'error': 'Invalid UID. Please check your UID.'}, status_code=400)
64
-
65
- except enkacard.enc_error.ENCardError:
66
- return JSONResponse(content={'error': 'Enable display of the showcase in the game or add characters there.'}, status_code=400)
67
-
68
- except Exception as e:
69
- return JSONResponse(content={'error': 'UNKNOWN ERR: ' + str(e)}, status_code=500)
70
-
71
- @app.get("/")
72
- def hello_world():
73
- return 'AMERICA YA HALLO!!'
74
-
75
- # @app.route("/update_char")
76
- # def upload():
77
- # data_dir = "/tmp/data"
78
-
79
- # if not os.path.exists(data_dir):
80
- # os.makedirs(data_dir)
81
-
82
- # data_dir = "/tmp/langs"
83
-
84
- # if not os.path.exists(data_dir):
85
- # os.makedirs(data_dir)
86
- # asyncio.run(update_genshin())
87
- # return 'Update smth ig!!'
88
-
89
-
90
-
91
- def upload_image(data):
92
- print(data)
93
- url = "https://fighter-programmer-uploader.hf.space/upload"
94
- files = {'file': ('file', data, "image/png")}
95
- response = requests.post(url, files=files)
96
-
97
- if response.status_code != 200:
98
- raise Exception(f"HTTP Error: {response.status_code}")
99
-
100
- try:
101
- body = response.json()
102
- if body["url"]:
103
- return body["url"]
104
- else:
105
- raise Exception(f"Telegraph error: {body.get('error', 'Unknown error')}")
106
- except (ValueError, KeyError, IndexError) as e:
107
- raise Exception(f"Failed to parse response: {str(e)}")
108
- def process_image(dt):
109
- with BytesIO() as byte_io:
110
- dt.card.save(byte_io, "PNG")
111
- byte_io.seek(0)
112
- image_url = upload_image(byte_io)
113
 
114
  return {
115
- "name": dt.name,
116
- "url": image_url
117
  }
118
-
119
- def process_images(result):
120
- characters = []
121
- with concurrent.futures.ThreadPoolExecutor() as executor:
122
- # Execute image uploads in parallel
123
- futures = [executor.submit(process_image, dt) for dt in result.card]
124
-
125
- for future in concurrent.futures.as_completed(futures):
126
- try:
127
- characters.append(future.result())
128
- except Exception as e:
129
- print(f"Error processing image: {e}")
130
 
131
- return characters
132
- if __name__ == "__main__":
133
- # data_dir = "/tmp/data"
134
-
135
- # if not os.path.exists(data_dir):
136
- # os.makedirs(data_dir)
137
-
138
- # data_dir = "/tmp/langs"
139
-
140
- # if not os.path.exists(data_dir):
141
- # os.makedirs(data_dir)
142
- # asyncio.run(update_genshin())
143
- uvicorn.run("main:app", host="0.0.0.0", port=7860, workers=8, timeout_keep_alive=60000)
144
- # import enkacard
145
- # import enkacard.encbanner
146
- # import enkanetwork
147
- # import asyncio
148
- # import requests
149
- # from io import BytesIO
150
- # from enkanetwork import EnkaNetworkAPI
151
- # import os
152
- # from contextlib import asynccontextmanager
153
-
154
- # from fastapi import FastAPI
155
-
156
- # from fastapi.responses import (
157
- # JSONResponse,
158
- # )
159
- # from enkacard import enkatools
160
-
161
- # import uvicorn
162
-
163
- # enka_update = EnkaNetworkAPI()
164
-
165
-
166
- # async def update_genshin():
167
- # try:
168
- # async with enka_update:
169
- # await enka_update.update_assets(path="/tmp", lang=["EN"])
170
-
171
-
172
- # # lang=["EN"],
173
- # print("Finished update")
174
- # except Exception as e:
175
- # print(f"Update failed: {e}")
176
-
177
- # async def card(id, designtype):
178
- # async with enkacard.encbanner.ENC(uid = str(id)) as encard:
179
- # return await encard.creat(template = (2 if str(designtype) == "2" else 1))
180
-
181
- # @asynccontextmanager
182
- # async def lifespan(app: FastAPI):
183
- # data_dir = "/tmp/data"
184
-
185
- # if not os.path.exists(data_dir):
186
- # os.makedirs(data_dir)
187
-
188
- # data_dir = "/tmp/langs"
189
-
190
- # if not os.path.exists(data_dir):
191
- # os.makedirs(data_dir)
192
- # await update_genshin()
193
- # yield
194
- # print("Goodbye")
195
-
196
- # app = FastAPI()
197
- # # app = FastAPI(lifespan=lifespan)
198
-
199
- # @app.get("/{id}") # Correct route definition without prefix
200
- # async def characters(id: int, design: str = "1"): # Use async and await
201
- # try:
202
- # characters = []
203
- # result = await card(id, design) # Use await instead of asyncio.run()
204
-
205
- # for dt in result.card:
206
- # with BytesIO() as byte_io:
207
- # dt.card.save(byte_io, "PNG")
208
- # byte_io.seek(0)
209
- # image_url = upload_image(byte_io)
210
-
211
- # characters.append({
212
- # "name": dt.name,
213
- # "url": image_url
214
- # })
215
-
216
- # # Return valid JSON response using FastAPI's JSONResponse
217
- # return JSONResponse(content={'response': characters})
218
-
219
- # except enkanetwork.exception.VaildateUIDError:
220
- # return JSONResponse(content={'error': 'Invalid UID. Please check your UID.'}, status_code=400)
221
-
222
- # except enkacard.enc_error.ENCardError:
223
- # return JSONResponse(content={'error': 'Enable display of the showcase in the game or add characters there.'}, status_code=400)
224
-
225
- # except Exception as e:
226
- # return JSONResponse(content={'error': 'UNKNOWN ERR: ' + str(e)}, status_code=500)
227
-
228
- # @app.get("/")
229
- # def hello_world():
230
- # return 'AMERICA YA HALLO!!'
231
-
232
- # # @app.route("/update_char")
233
- # # def upload():
234
- # # data_dir = "/tmp/data"
235
-
236
- # # if not os.path.exists(data_dir):
237
- # # os.makedirs(data_dir)
238
-
239
- # # data_dir = "/tmp/langs"
240
-
241
- # # if not os.path.exists(data_dir):
242
- # # os.makedirs(data_dir)
243
- # # asyncio.run(update_genshin())
244
- # # return 'Update smth ig!!'
245
-
246
-
247
-
248
- # def upload_image(data):
249
- # url = "https://telegra.ph/upload"
250
- # files = {'file': ('file', data, "image/png")}
251
- # response = requests.post(url, files=files)
252
-
253
- # if response.status_code != 200:
254
- # raise Exception(f"HTTP Error: {response.status_code}")
255
-
256
- # try:
257
- # body = response.json()
258
- # if isinstance(body, list) and 'src' in body[0]:
259
- # return "https://telegra.ph" + body[0]['src']
260
- # else:
261
- # raise Exception(f"Telegraph error: {body.get('error', 'Unknown error')}")
262
- # except (ValueError, KeyError, IndexError) as e:
263
- # raise Exception(f"Failed to parse response: {str(e)}")
264
-
265
- # if __name__ == "__main__":
266
- # data_dir = "/tmp/data"
267
-
268
- # if not os.path.exists(data_dir):
269
- # os.makedirs(data_dir)
270
 
271
- # data_dir = "/tmp/langs"
 
 
 
 
 
 
 
272
 
273
- # if not os.path.exists(data_dir):
274
- # os.makedirs(data_dir)
275
- # asyncio.run(update_genshin())
276
- # uvicorn.run("main:app", host="0.0.0.0", port=7860, workers=8, timeout_keep_alive=600)
 
 
 
1
  import os
2
+ import uuid
3
+ import tempfile
4
+ import httpx
5
+ import torch
6
+ from PIL import Image
7
+ from fastapi import FastAPI, Query, HTTPException
8
+ from transformers import AutoModelForImageClassification, ViTImageProcessor
9
+ from typing import Optional
10
+
11
+ # Initialize the model and processor globally to avoid reloading for each request
12
+ model = AutoModelForImageClassification.from_pretrained("Falconsai/nsfw_image_detection")
13
+ processor = ViTImageProcessor.from_pretrained('Falconsai/nsfw_image_detection')
14
+
15
+ app = FastAPI(title="NSFW Image Detection API")
16
+
17
+ @app.get("/detect")
18
+ async def detect_nsfw(
19
+ url: str = Query(..., description="URL of the image to analyze"),
20
+ timeout: Optional[int] = Query(default=10, description="Timeout for downloading image in seconds")
21
+ ):
22
+ """
23
+ Detect NSFW content in an image from a given URL.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ - Saves the image to a temporary file
26
+ - Processes the image using a pre-trained NSFW detection model
27
+ - Returns the highest confidence prediction
28
+ """
29
  try:
30
+ # Get the system's temporary directory
31
+ temp_dir = tempfile.gettempdir()
32
+ temp_filename = os.path.join(temp_dir, f"{uuid.uuid4()}.jpg")
33
+
34
+ # Download the image
35
+ async with httpx.AsyncClient() as client:
36
+ response = await client.get(url, timeout=timeout)
37
+ response.raise_for_status()
38
+
39
+ # Save the image
40
+ with open(temp_filename, 'wb') as f:
41
+ f.write(response.content)
42
+
43
+ # Open and process the image
44
+ img = Image.open(temp_filename)
45
+
46
+ # Perform inference
47
+ with torch.no_grad():
48
+ inputs = processor(images=img, return_tensors="pt")
49
+ outputs = model(**inputs)
50
+ logits = outputs.logits
51
+
52
+ # Calculate softmax probabilities
53
+ confidences = torch.softmax(logits, dim=-1)
54
+
55
+ # Find the label with the highest confidence
56
+ max_confidence_id = confidences[0].argmax().item()
57
+ max_label = model.config.id2label[max_confidence_id]
58
+ max_confidence = confidences[0][max_confidence_id].item()
59
+
60
+ # Clean up the temporary file
61
+ os.unlink(temp_filename)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  return {
64
+ "label": max_label,
65
+ "confidence": max_confidence
66
  }
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
+ except httpx.RequestError as e:
69
+ raise HTTPException(status_code=400, detail=f"Error downloading image: {str(e)}")
70
+ except Exception as e:
71
+ raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
+ # Startup event to warm up the model
74
+ @app.on_event("startup")
75
+ async def startup_event():
76
+ # Perform a dummy inference to warm up the model
77
+ dummy_img = Image.new('RGB', (224, 224), color='red')
78
+ with torch.no_grad():
79
+ inputs = processor(images=dummy_img, return_tensors="pt")
80
+ model(**inputs)
81
 
82
+ if __name__ == "__main__":
83
+ import uvicorn
84
+ uvicorn.run(app, host="0.0.0.0", port=7860)