File size: 3,420 Bytes
2334910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from botasaurus.browser import browser, Driver
import time
import uvicorn

app = FastAPI()

class RequestData(BaseModel):
    text: str
    service: str = "clever"

@browser(
    headless=True,
    block_images=True,
    reuse_driver=True, # Оставляем браузер открытым для скорости последующих запросов
    cache=False
)
def humanize_task(driver: Driver, text):
    url = "https://cleverhumanizer.ai/"
    
    # 1. Загрузка страницы
    if url not in driver.current_url:
        print(f"Navigating to {url}")
        driver.get(url)
        time.sleep(8)
    
    # 2. Очистка и ввод текста (используем индекс 0 - первый редактор на странице)
    print("Finding editors...")
    editors = driver.select_all('.ql-editor')
    if len(editors) < 2:
        print("Not enough editors found. Refreshing...")
        driver.get(url)
        time.sleep(8)
        editors = driver.select_all('.ql-editor')
    
    if not editors:
        return "ERROR: No editors found"

    print("Typing text into Editor[0]...")
    in_editor = editors[0]
    # Очистка через JS
    driver.driver.execute_script("arguments[0].innerText = '';", in_editor.element)
    in_editor.type(text)
    time.sleep(2)

    # 3. Клик по кнопке (используем индекс 0 - первая кнопка .submitQuill)
    btns = driver.select_all('.submitQuill')
    if btns:
        print("Clicking Submit Button[0]...")
        driver.driver.execute_script("arguments[0].scrollIntoView();", btns[0].element)
        driver.driver.execute_script("arguments[0].click();", btns[0].element)
    else:
        return "ERROR: Submit button not found"

    # 4. Ожидание результата в Editor[1]
    print("Waiting for generation...")
    for i in range(45): # Ждем до 90 секунд
        time.sleep(2)
        # Получаем свежий список редакторов
        current_editors = driver.select_all('.ql-editor')
        if len(current_editors) >= 2:
            out_text = current_editors[1].text.strip()
            # Если текст появился и это не заглушка
            if out_text and len(out_text) > 10 and "New text will appear" not in out_text:
                print("Success! Result captured.")
                return out_text
        
        if i % 5 == 0:
            print(f"Still waiting... ({i*2}s)")
                
    return "TIMEOUT: Generation is too slow or failed"

@app.post("/humanize")
def humanize(data: RequestData):
    print(f"Received request for service: {data.service}")
    if data.service == "clever":
        try:
            result = humanize_task(data.text)
            if "ERROR" in result or "TIMEOUT" in result:
                raise HTTPException(status_code=500, detail=result)
            return {"result": result}
        except Exception as e:
            print(f"Task Exception: {str(e)}")
            raise HTTPException(status_code=500, detail=str(e))
    else:
        return {"error": "Only 'clever' service is supported currently"}

@app.get("/")
def health():
    return {"status": "alive", "service": "AI Humanizer API"}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7860)