Hana Celeste commited on
Commit
e9ea4c6
·
verified ·
1 Parent(s): ce5419a

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +48 -53
main.py CHANGED
@@ -3,44 +3,55 @@ import requests
3
  import time
4
  from fastapi import FastAPI
5
  from playwright.async_api import async_playwright
 
6
 
7
- app = FastAPI()
8
-
9
- # Cấu hình API mới
10
  FREEIMAGE_API_KEY = "6d207e02198a847aa98d0a2a901485a5"
11
  FREEIMAGE_URL = "https://freeimage.host/api/1/upload"
12
 
13
- async def get_page(uid: str, fast_mode=False):
14
- p = await async_playwright().start()
15
- browser = await p.chromium.launch(headless=True, args=[
16
- '--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu'
17
- ])
18
- context = await browser.new_context(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  viewport={'width': 1280, 'height': 800},
20
  user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
21
  )
22
  page = await context.new_page()
23
-
24
- async def block_waste(route):
25
- bad_types = ["media", "font", "other"]
26
- if fast_mode: bad_types.extend(["image", "stylesheet"])
27
- if any(x in route.request.url for x in ["google", "analytics", "doubleclick"]):
28
- await route.abort()
29
- else:
30
- await route.continue_()
31
-
32
- await page.route("**/*", block_waste)
33
- await page.goto(f"https://enka.network/u/{uid}/", wait_until="domcontentloaded", timeout=60000)
34
- return browser, page
35
 
36
  @app.get("/info")
37
  async def info(uid: str):
38
  start_time = time.time()
39
- browser, page = await get_page(uid, fast_mode=True)
40
  try:
 
 
 
41
  try:
42
- await page.click('button[data-icon="cards"]', timeout=2000)
43
- await page.wait_for_selector('.Loda .bg', timeout=2000)
44
  except: pass
45
 
46
  data = await page.evaluate("""
@@ -81,30 +92,29 @@ async def info(uid: str):
81
  };
82
  }
83
  """)
84
- await browser.close()
85
  return {"execution_time": f"{round(time.time() - start_time, 2)}s", "uid": uid, **data}
86
  except Exception as e:
87
- if 'browser' in locals(): await browser.close()
88
  return {"error": str(e)}
89
 
90
  @app.get("/gen")
91
  async def generate(uid: str, char: str = None):
92
  start_time = time.time()
93
- browser, page = await get_page(uid, fast_mode=False)
94
  try:
 
 
95
  if char:
96
  target = char.strip().capitalize()
97
  try:
98
- # Tìm chính xác avatar chứa tên nhân vật
99
- await page.click(f"//div[contains(@class, 'avatar')]//figure[contains(@style, '{target}')]", timeout=5000)
100
- await asyncio.sleep(0.5) # Giảm tối đa thời gian chờ render
101
  except: pass
102
 
103
  await page.click('button[data-icon="image"]')
104
- # Chờ ảnh blob sẵn sàng
105
- await page.wait_for_selector('.Loda img[src^="blob:"]', timeout=15000)
106
 
107
- # Chuyển blob sang base64 ngay trong trình duyệt
108
  img_base64 = await page.evaluate("""
109
  async () => {
110
  const img = document.querySelector('.Loda img');
@@ -117,34 +127,19 @@ async def generate(uid: str, char: str = None):
117
  });
118
  }
119
  """)
120
- await browser.close()
121
 
122
- # Gọi API FreeImage.host
123
- res = requests.post(
124
- FREEIMAGE_URL,
125
- data={
126
- "key": FREEIMAGE_API_KEY,
127
- "action": "upload",
128
- "source": img_base64,
129
- "format": "json"
130
- },
131
- timeout=20
132
- )
133
-
134
- # Lấy link ảnh từ cấu trúc JSON của FreeImage
135
- json_res = res.json()
136
- card_url = json_res.get('image', {}).get('url', "Upload Failed")
137
 
138
  return {
139
  "execution_time": f"{round(time.time() - start_time, 2)}s",
140
  "uid": uid,
141
- "char": char or "default",
142
- "card_url": card_url
143
  }
144
  except Exception as e:
145
- if 'browser' in locals(): await browser.close()
146
  return {"error": str(e)}
147
 
148
  @app.get("/")
149
  def home():
150
- return {"status": "Enka API Speed-Optimized with FreeImage.host"}
 
3
  import time
4
  from fastapi import FastAPI
5
  from playwright.async_api import async_playwright
6
+ from contextlib import asynccontextmanager
7
 
8
+ # Cấu hình API
 
 
9
  FREEIMAGE_API_KEY = "6d207e02198a847aa98d0a2a901485a5"
10
  FREEIMAGE_URL = "https://freeimage.host/api/1/upload"
11
 
12
+ # Biến toàn cục để giữ trình duyệt
13
+ browser_manager = {"browser": None, "playwright": None}
14
+
15
+ @asynccontextmanager
16
+ async def lifespan(app: FastAPI):
17
+ # Khởi tạo trình duyệt khi Server bắt đầu
18
+ browser_manager["playwright"] = await async_playwright().start()
19
+ browser_manager["browser"] = await browser_manager["playwright"].chromium.launch(
20
+ headless=True,
21
+ args=['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage']
22
+ )
23
+ print("🚀 Browser đã sẵn sàng!")
24
+ yield
25
+ # Đóng trình duyệt khi Server tắt
26
+ await browser_manager["browser"].close()
27
+ await browser_manager["playwright"].stop()
28
+
29
+ app = FastAPI(lifespan=lifespan)
30
+
31
+ async def get_fast_page(fast_mode=False):
32
+ # Tạo context mới (nhanh hơn tạo browser mới)
33
+ context = await browser_manager["browser"].new_context(
34
  viewport={'width': 1280, 'height': 800},
35
  user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
36
  )
37
  page = await context.new_page()
38
+
39
+ if fast_mode:
40
+ await page.route("**/*", lambda route: route.abort() if route.request.resource_type in ["media", "font"] else route.continue_())
41
+
42
+ return context, page
 
 
 
 
 
 
 
43
 
44
  @app.get("/info")
45
  async def info(uid: str):
46
  start_time = time.time()
47
+ context, page = await get_fast_page(fast_mode=True)
48
  try:
49
+ await page.goto(f"https://enka.network/u/{uid}/", wait_until="domcontentloaded", timeout=30000)
50
+
51
+ # Click Namecard nhanh
52
  try:
53
+ await page.click('button[data-icon="cards"]', timeout=1500)
54
+ await page.wait_for_selector('.Loda .bg', timeout=1500)
55
  except: pass
56
 
57
  data = await page.evaluate("""
 
92
  };
93
  }
94
  """)
95
+ await context.close()
96
  return {"execution_time": f"{round(time.time() - start_time, 2)}s", "uid": uid, **data}
97
  except Exception as e:
98
+ await context.close()
99
  return {"error": str(e)}
100
 
101
  @app.get("/gen")
102
  async def generate(uid: str, char: str = None):
103
  start_time = time.time()
104
+ context, page = await get_fast_page(fast_mode=False)
105
  try:
106
+ await page.goto(f"https://enka.network/u/{uid}/", wait_until="domcontentloaded", timeout=30000)
107
+
108
  if char:
109
  target = char.strip().capitalize()
110
  try:
111
+ await page.click(f"//div[contains(@class, 'avatar')]//figure[contains(@style, '{target}')]", timeout=3000)
112
+ await asyncio.sleep(0.4)
 
113
  except: pass
114
 
115
  await page.click('button[data-icon="image"]')
116
+ await page.wait_for_selector('.Loda img[src^="blob:"]', timeout=10000)
 
117
 
 
118
  img_base64 = await page.evaluate("""
119
  async () => {
120
  const img = document.querySelector('.Loda img');
 
127
  });
128
  }
129
  """)
130
+ await context.close()
131
 
132
+ res = requests.post(FREEIMAGE_URL, data={"key": FREEIMAGE_API_KEY, "action": "upload", "source": img_base64, "format": "json"}, timeout=15)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
  return {
135
  "execution_time": f"{round(time.time() - start_time, 2)}s",
136
  "uid": uid,
137
+ "card_url": res.json().get('image', {}).get('url')
 
138
  }
139
  except Exception as e:
140
+ await context.close()
141
  return {"error": str(e)}
142
 
143
  @app.get("/")
144
  def home():
145
+ return {"status": "Warm-up Browser API Live"}