File size: 1,718 Bytes
ade4f6a
 
 
 
 
3e14b46
ade4f6a
 
 
 
 
 
 
 
 
 
 
6b3e951
 
ade4f6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import time
from typing import Literal

from playwright.sync_api import Playwright, sync_playwright

from lib.pages import TranslatorPage
from environment import DEBUG_PORT, RunType

class PageRunner:
    def __init__(self, run_type: RunType):
        self.run_type = run_type

    def start(self, p: Playwright)-> TranslatorPage:
        if self.run_type == RunType.electron:
            return TranslatorPage(self._start_electron(p))
        elif self.run_type == RunType.code:
            return TranslatorPage(self._start_web(p))
        elif self.run_type == RunType.dev:
            return TranslatorPage(self._start_web(p))
        else:
            raise TypeError(f"invalid run_type: {self.run_type}")

    def _start_web(self, p: Playwright):
        url = "http://127.0.0.1:9191/app"
        browser = p.chromium.launch(headless=False)
        context = browser.new_context(permissions=['microphone'])
        page = context.new_page()
        for i in range(20):
            try:
                page.goto(url)
                break
            except Exception as e:
                print(f"Exception happened: {e}. retry {i+1}...")
                time.sleep(3)
        return page

    def _start_electron(self, p: Playwright):
        # 连接到已开启的 Electron 调试端口
        browser = p.chromium.connect_over_cdp(f"http://localhost:{DEBUG_PORT}")
        assert browser.is_connected()
        print("connected to electron debugging port")
        context = browser.contexts[0]
        page = context.pages[0]
        return page

if __name__ == '__main__':
    with sync_playwright() as p:
        page = PageRunner(RunType.code).start(p)
        page.start_zh2en()
        page.set_off()