Reflectus commited on
Commit
2334910
·
verified ·
1 Parent(s): 7981d96

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +94 -0
app.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from pydantic import BaseModel
3
+ from botasaurus.browser import browser, Driver
4
+ import time
5
+ import uvicorn
6
+
7
+ app = FastAPI()
8
+
9
+ class RequestData(BaseModel):
10
+ text: str
11
+ service: str = "clever"
12
+
13
+ @browser(
14
+ headless=True,
15
+ block_images=True,
16
+ reuse_driver=True, # Оставляем браузер открытым для скорости последующих запросов
17
+ cache=False
18
+ )
19
+ def humanize_task(driver: Driver, text):
20
+ url = "https://cleverhumanizer.ai/"
21
+
22
+ # 1. Загрузка страницы
23
+ if url not in driver.current_url:
24
+ print(f"Navigating to {url}")
25
+ driver.get(url)
26
+ time.sleep(8)
27
+
28
+ # 2. Очистка и ввод текста (используем индекс 0 - первый редактор на странице)
29
+ print("Finding editors...")
30
+ editors = driver.select_all('.ql-editor')
31
+ if len(editors) < 2:
32
+ print("Not enough editors found. Refreshing...")
33
+ driver.get(url)
34
+ time.sleep(8)
35
+ editors = driver.select_all('.ql-editor')
36
+
37
+ if not editors:
38
+ return "ERROR: No editors found"
39
+
40
+ print("Typing text into Editor[0]...")
41
+ in_editor = editors[0]
42
+ # Очистка через JS
43
+ driver.driver.execute_script("arguments[0].innerText = '';", in_editor.element)
44
+ in_editor.type(text)
45
+ time.sleep(2)
46
+
47
+ # 3. Клик по кнопке (используем индекс 0 - первая кнопка .submitQuill)
48
+ btns = driver.select_all('.submitQuill')
49
+ if btns:
50
+ print("Clicking Submit Button[0]...")
51
+ driver.driver.execute_script("arguments[0].scrollIntoView();", btns[0].element)
52
+ driver.driver.execute_script("arguments[0].click();", btns[0].element)
53
+ else:
54
+ return "ERROR: Submit button not found"
55
+
56
+ # 4. Ожидание результата в Editor[1]
57
+ print("Waiting for generation...")
58
+ for i in range(45): # Ждем до 90 секунд
59
+ time.sleep(2)
60
+ # Получаем свежий список редакторов
61
+ current_editors = driver.select_all('.ql-editor')
62
+ if len(current_editors) >= 2:
63
+ out_text = current_editors[1].text.strip()
64
+ # Если текст появился и это не заглушка
65
+ if out_text and len(out_text) > 10 and "New text will appear" not in out_text:
66
+ print("Success! Result captured.")
67
+ return out_text
68
+
69
+ if i % 5 == 0:
70
+ print(f"Still waiting... ({i*2}s)")
71
+
72
+ return "TIMEOUT: Generation is too slow or failed"
73
+
74
+ @app.post("/humanize")
75
+ def humanize(data: RequestData):
76
+ print(f"Received request for service: {data.service}")
77
+ if data.service == "clever":
78
+ try:
79
+ result = humanize_task(data.text)
80
+ if "ERROR" in result or "TIMEOUT" in result:
81
+ raise HTTPException(status_code=500, detail=result)
82
+ return {"result": result}
83
+ except Exception as e:
84
+ print(f"Task Exception: {str(e)}")
85
+ raise HTTPException(status_code=500, detail=str(e))
86
+ else:
87
+ return {"error": "Only 'clever' service is supported currently"}
88
+
89
+ @app.get("/")
90
+ def health():
91
+ return {"status": "alive", "service": "AI Humanizer API"}
92
+
93
+ if __name__ == "__main__":
94
+ uvicorn.run(app, host="0.0.0.0", port=7860)