import aiohttp.web, asyncio, urllib.parse, pathlib, builtins, numpy, PIL.Image, io, sys, math, os, uvloop, lxml.etree, re, json, av, itertools, datetime, fake_useragent, huggingface_hub, time, traceback
from modelscope.hub.api import HubApi
# use chatgpt to create narration say limit to 35 to 40 english words

scripts = [
    # chapter 1
    {
        "narration": "Nearly eighty years old, Trump has recently appeared in public with a noticeably reduced schedule, drawing early attention from observers. Analysts note slower cadence, raising questions about stamina, scheduling, and public perception.",
        "prompt": "Daytime, natural daylight, soft light, side lighting, mid shot, centered composition. Trump in a dark suit stands briefly on outdoor steps, pauses, adjusts his cuff, then turns to walk away at a slower pace. Staff move calmly in the background as tree shadows sway lightly."
    },
    {
        "narration": "As President Trump himself, his public calendar shows fewer daily appearances, with activity density visibly lower than in previous years. Observers note slower cadence, raising questions about stamina, scheduling strategy, and public perception while aides coordinate carefully.",
        "prompt": "Daytime, bright daylight, soft light, medium-wide shot, centered composition. Trump exits a building entrance, stops momentarily at the steps, gestures briefly toward the front, then proceeds into a vehicle. Security remains motionless under steady light."
    },
    {
        "narration": "White House reporters have noted that Trump now limits extended press interactions, often departing shortly after brief statements. Analysts suggest the pattern raises questions regarding stamina, public energy, scheduling efficiency, and overall visibility management.",
        "prompt": "Daytime, natural daylight, soft light, medium close-up, centered composition. Trump speaks briefly at a podium, lips moving quickly, then gives a small nod and lowers his hand to signal an end. Camera operators adjust position in the background."
    },
    {
        "narration": "Public footage indicates that President Trump is frequently accompanied by staff during arrivals and departures, with stop durations carefully managed. Observers note deliberate timing, measured pace, and visible attention to public perception and energy conservation.",
        "prompt": "Daytime, daylight through hallway windows, soft light, mid shot, centered composition. Trump walks steadily along a corridor with aides at half-step distance. Floor reflections extend forward as the group moves in sync."
    },
    {
        "narration": "Media analysis suggests Trump's recent travel frequency has declined, marking a shift from his previously intensive public itinerary. The reduced tempo attracts attention to strategic pacing and observable signs of energy management.",
        "prompt": "Daytime, natural daylight, soft light, wide shot, centered composition. Trump makes a brief appearance near an aircraft, raises a hand in acknowledgment, then turns away. The aircraft remains still as clouds drift slowly overhead."
    },
    {
        "narration": "At several formal ceremonies, President Trump’s appearance order has been shifted later, with participation segments simplified. Observers note the adjusted schedule reflects careful management of stamina, energy, and public engagement across events.",
        "prompt": "Daytime, daylight, soft light, mid shot, centered composition. Trump waits at the edge of a ceremonial area, straightens his tie, steps forward to complete a short gesture, then retreats calmly. Other attendees remain in place."
    },
    {
        "narration": "Some commentators view Trump’s compressed schedule as a recalibration aimed at balancing personal energy and public duties. Analysts highlight the visible pacing, shorter engagements, and strategic presence optimization to maintain public impact over time.",
        "prompt": "Daytime, mixed daylight and practical lighting, soft light, mid shot, centered composition. Trump sits at a conference table, flips through documents, closes them, then leans slightly back as a briefing concludes."
    },
    {
        "narration": "White House sources say Trump increasingly favors closed-door meetings over large-scale public events and ceremonies. Observers note the visible preference for controlled settings, reflecting careful management of energy, focus, and operational efficiency.",
        "prompt": "Daytime, daylight through windows, soft light, side lighting, mid shot, centered composition. Trump takes a seat in a meeting room, raises a hand to signal the start of discussion as others sit down around the table."
    },
    {
        "narration": "From a visual rhythm perspective, each Trump appearance now fits within a tightly controlled and shortened time window. Analysts note consistent pacing, deliberate pauses, and a clearly defined public presence across various engagements.",
        "prompt": "Daytime, natural daylight, soft light, medium close-up, centered composition. Trump completes a brief statement within a designated area, then immediately turns and exits as staff begin clearing the space."
    },
    {
        "narration": "Overall, Trump’s increasingly compact schedule represents the first public signal prompting discussion of his physical condition. Observers analyze the structured timing, controlled movements, and apparent energy conservation during public appearances.",
        "prompt": "Daytime, daylight, soft light, mid shot, centered composition. Trump walks down a long corridor at a measured pace, his figure gradually receding as overhead lights extend into depth."
    },
    # chapter 2
    {
        "narration": "In recent weeks, Trump’s public appearances have followed a more predictable rhythm, with shorter durations and fewer unscheduled movements. Analysts observe deliberate pacing, measured steps, and carefully controlled interaction with staff and attendees.",
        "prompt": "Daytime, natural daylight, soft light, mid shot, centered composition. Trump walks into an indoor venue, pauses briefly under the lights, then takes a measured step forward as staff maintain distance behind him."
    },
    {
        "narration": "Several aides disclosed that Trump now adheres strictly to pre-planned routes and time limits during official events. Observers note the clearly defined pathways, strict timing adherence, and visible management of stamina and public presence.",
        "prompt": "Daytime, daylight through windows, soft light, medium-wide shot, centered composition. Trump advances along a marked pathway inside a government building, footsteps steady, staff positioned evenly along the sides."
    },
    {
        "narration": "Observers noted that Trump avoids prolonged standing, often transitioning quickly between arrival, appearance, and departure. Analysts highlight shorter engagements, intentional pacing, and deliberate timing to maintain energy efficiency and operational control.",
        "prompt": "Daytime, natural daylight, soft light, mid shot, centered composition. Trump stands briefly at a designated spot, acknowledges the audience with a nod, then turns smoothly to exit."
    },
    {
        "narration": "Footage analysis shows that Trump’s pauses between movements have increased, suggesting deliberate pacing rather than spontaneity. Analysts observe controlled speed, strategic timing, and carefully measured public appearances to conserve energy and maintain public image.",
        "prompt": "Daytime, daylight, soft light, medium close-up, centered composition. Trump slows near a corridor intersection, pauses for a second, then resumes walking with controlled steps."
    },
    {
        "narration": "Event organizers confirmed that Trump’s schedules now include buffer periods to prevent physical overexertion. Observers note visible energy management, intentional pauses, and structured timing that allow for recovery between appearances.",
        "prompt": "Daytime, soft daylight, mid shot, centered composition. Trump waits calmly in a holding area, hands relaxed at his sides, while staff quietly coordinate timing nearby."
    },
    {
        "narration": "During press moments, Trump typically delivers concise remarks before signaling an end without extended exchanges. Analysts note efficient communication, minimal physical demand, and structured interaction with media personnel to maintain stamina.",
        "prompt": "Daytime, natural daylight, soft light, medium close-up, centered composition. Trump speaks briefly at a microphone, lowers his hand, and steps back as aides move in."
    },
    {
        "narration": "Sources close to Trump emphasize that these changes were implemented gradually, avoiding abrupt disruptions to public routines. Observers note structured pacing, strategic energy allocation, and deliberate management of public engagements over time.",
        "prompt": "Daytime, daylight, soft light, mid shot, centered composition. Trump walks alongside aides at an even pace, the group moving smoothly through a hallway."
    },
    {
        "narration": "From a logistical standpoint, Trump’s appearances are now structured to minimize unplanned physical demands. Analysts highlight clearly defined routes, controlled movement, and visible attention to energy conservation and consistent public presence.",
        "prompt": "Daytime, natural daylight, soft light, wide shot, centered composition. Trump follows a clearly defined route across an event space, with barriers guiding movement."
    },
    {
        "narration": "Media commentators interpret Trump’s disciplined pacing as a calculated approach to sustaining long-term visibility. Observers note precise timing, limited pauses, and carefully orchestrated public appearances that maximize presence while minimizing exertion.",
        "prompt": "Daytime, daylight, soft light, mid shot, centered composition. Trump maintains an upright posture while moving forward, background figures remaining still."
    },
    {
        "narration": "Taken together, these adjustments mark a clear contrast with Trump’s previously fast-paced and spontaneous public style. Analysts observe the structured schedule, controlled appearances, and emphasis on energy management and measured interaction.",
        "prompt": "Daytime, daylight, soft light, mid shot, centered composition. Trump exits an event area calmly, movement steady as the surrounding space gradually empties."
    },
    # chapter 3
    {
        "narration": "Recent medical observations have drawn attention to visible physical changes in Trump, including noticeable weight reduction over several months. Analysts discuss possible lifestyle, health, and stamina implications in light of the structured schedule.",
        "prompt": "Daytime, natural daylight from large windows, soft light, mid shot, centered composition. Trump walks slowly across a conference room, suit hanging looser on his frame, fabric shifting as he moves."
    },
    {
        "narration": "Public footage compared across events suggests Trump’s facial contours appear slimmer than in previous campaign cycles. Observers highlight defined jawline, leaner profile, and subtle indicators of physical changes, attracting scrutiny from analysts and media.",
        "prompt": "Daytime, daylight, soft light, medium close-up, centered composition. Trump turns his head slightly toward cameras, jawline more defined, facial muscles tightening briefly as he speaks."
    },
    {
        "narration": "Analysts reviewing archived recordings note a gradual change rather than an abrupt physical transformation. Observers highlight incremental shifts, careful pacing, and measured public appearances consistent with long-term health management strategies.",
        "prompt": "Daytime, diffuse daylight, soft light, mid shot, centered composition. Trump stands still as background screens display blurred archival images, then shifts his weight gently."
    },
    {
        "narration": "Medical experts caution that weight loss at an advanced age can stem from deliberate lifestyle changes or underlying health factors. Observers stress careful monitoring, structured routines, and visible pacing during public engagements as indicators.",
        "prompt": "Daytime, indoor daylight, soft light, wide shot, balanced composition. Trump sits briefly before standing again, movement deliberate, aides positioned quietly around the room."
    },
    {
        "narration": "Trump himself has not publicly addressed these observations, leaving room for continued interpretation and speculation. Analysts discuss possible causes, including schedule adjustments, energy management, and gradual physical conditioning to maintain public appearances.",
        "prompt": "Daytime, daylight, soft light, medium close-up, centered composition. Trump looks ahead without comment, blinks once, then adjusts his stance."
    },
    {
        "narration": "Supporters argue that the changes reflect disciplined routines rather than any sign of physical decline. Analysts note structured pacing, controlled interactions, and energy-conscious scheduling as evidence of intentional management rather than health concerns.",
        "prompt": "Daytime, natural daylight, soft light, mid shot, centered composition. Trump walks forward steadily, shoulders squared, steps measured and consistent."
    },
    {
        "narration": "Critics, however, question whether the physical changes align with reduced public stamina. Observers highlight visible pauses, deliberate movement, and reduced spontaneous interactions, prompting ongoing discussion about energy levels and endurance at advanced age.",
        "prompt": "Daytime, daylight, soft light, mid shot, centered composition. Trump pauses briefly during movement, then resumes walking as cameras track from the front."
    },
    {
        "narration": "Event photographers have increasingly captured moments of rest between Trump’s scheduled appearances. Analysts note these pauses as intentional energy conservation strategies, reflecting careful management of stamina and public engagement during prolonged sequences of events.",
        "prompt": "Daytime, indoor daylight, soft light, medium-wide shot, centered composition. Trump stands in a quiet side area, hands loosely clasped, breathing steady."
    },
    {
        "narration": "Comparative timelines indicate that the changes became more pronounced following schedule compression earlier this year. Analysts highlight controlled pacing, observable weight reduction, and deliberate engagement strategies to optimize stamina and public visibility.",
        "prompt": "Daytime, natural daylight, soft light, wide shot, centered composition. Trump transitions between two locations, movement framed by guiding barriers."
    },
    {
        "narration": "As visual records accumulate, Trump’s physical condition remains a subtle but growing point of public attention. Observers note careful pacing, structured appearances, and deliberate timing consistent with energy management strategies and health maintenance.",
        "prompt": "Daytime, daylight, soft light, medium close-up, centered composition. Trump looks forward, then turns slightly away as the background activity continues."
    },
    # chapter 4
    {
        "narration": "Questions surrounding Trump’s health have intensified as medical transparency remains limited amid ongoing public speculation. Analysts highlight visible pacing, measured appearances, and energy management as potential indicators of stamina and long-term health considerations.",
        "prompt": "Daytime, natural daylight from overhead fixtures, soft light, mid shot, centered composition. Trump walks into a briefing space, pauses momentarily, then adjusts his posture as cameras remain fixed."
    },
    {
        "narration": "Official statements consistently describe Trump as fit for duty, though they provide few new clinical details. Observers highlight the contrast between public messaging and visible patterns of structured energy management during appearances.",
        "prompt": "Daytime, indoor daylight, soft light, medium close-up, centered composition. Trump stands at a podium, nods once, then lowers his gaze briefly before looking forward."
    },
    {
        "narration": "The lack of updated medical reports has fueled debate among analysts and commentators across media outlets. Observers note that visual cues, pacing, and movement patterns influence public perception more than confirmed clinical data.",
        "prompt": "Daytime, diffuse daylight, soft light, wide shot, balanced composition. Trump moves through a press area while blurred figures and equipment line the background."
    },
    {
        "narration": "Historically, Trump has favored selective disclosure regarding personal health information. Analysts and commentators note patterns of controlled visibility, energy management, and deliberate pacing consistent with limited transparency strategies.",
        "prompt": "Daytime, natural daylight, soft light, mid shot, centered composition. Trump walks past a corridor window, light shifting across his face as he turns slightly."
    },
    {
        "narration": "White House aides maintain that no unusual medical interventions are taking place behind the scenes. Observers note structured pacing, energy management, and controlled public appearances as evidence of careful operational planning.",
        "prompt": "Daytime, indoor daylight, soft light, medium shot, centered composition. Trump stands still while aides remain positioned several steps behind, minimal movement."
    },
    {
        "narration": "Health experts note that limited data makes objective assessment difficult without verified examinations. Analysts rely on observable patterns of movement, pacing, and scheduling to infer potential energy conservation or stamina concerns.",
        "prompt": "Daytime, daylight, soft light, wide shot, centered composition. Trump transitions from one room to another, footsteps measured as doors open ahead."
    },
    {
        "narration": "Public concern appears shaped more by visual cues than by confirmed medical evidence. Observers emphasize structured movements, measured pacing, and controlled engagement as signals influencing perceptions of stamina and overall health.",
        "prompt": "Daytime, natural daylight, soft light, medium close-up, centered composition. Trump pauses, blinks, then resumes walking as cameras follow."
    },
    {
        "narration": "Supporters frequently dismiss health rumors as politically motivated narratives. Analysts note that structured pacing, controlled appearances, and deliberate scheduling may reinforce public confidence among aligned observers.",
        "prompt": "Daytime, daylight, soft light, mid shot, centered composition. Trump advances steadily, shoulders squared, background figures remaining static."
    },
    {
        "narration": "Critics argue that greater disclosure would help stabilize public confidence. Observers note visible patterns, pacing, and structured appearances as partial evidence, but lack of official data fuels continued speculation.",
        "prompt": "Daytime, indoor daylight, soft light, medium-wide shot, balanced composition. Trump stands near a doorway, shifts his weight slightly, then turns."
    },
    {
        "narration": "Until clearer information emerges, Trump’s health remains an unresolved dimension of public debate. Analysts highlight careful energy management, structured engagement, and deliberate pacing as consistent features of observable appearances.",
        "prompt": "Daytime, daylight, soft light, mid shot, centered composition. Trump exits the scene calmly, movement steady as the space behind him clears."
    },
    # chapter 5
    {
        "narration": "Behind the scenes, Trump’s daily workload has reportedly been adjusted to prioritize energy conservation and controlled pacing. Analysts observe structured timing, deliberate engagement, and minimized physical strain during public and private activities.",
        "prompt": "Daytime, natural daylight through tall windows, soft light, mid shot, centered composition. Trump sits briefly at a desk, rises slowly, straightens his jacket, and takes a measured step forward while papers remain neatly arranged."
    },
    {
        "narration": "Multiple sources indicate that meetings involving Trump are now shorter and more tightly structured than in previous years. Observers note efficiency, deliberate timing, and energy-conscious scheduling as defining elements of his routine.",
        "prompt": "Daytime, indoor daylight, soft light, medium-wide shot, balanced composition. Trump enters a meeting room, nods once to attendees, gestures lightly, then moves toward his designated seat."
    },
    {
        "narration": "Advisers emphasize that efficiency, rather than intensity, now defines Trump’s approach to daily responsibilities. Analysts note structured pacing, measured engagement, and deliberate energy management guiding decisions and interactions throughout the day.",
        "prompt": "Daytime, daylight, soft light, mid shot, centered composition. Trump reviews documents, turns a page deliberately, then sets the folder down and looks ahead."
    },
    {
        "narration": "Personal schedules reportedly allow extended breaks between public-facing engagements. Observers note carefully spaced activities, deliberate pacing, and energy conservation as part of a comprehensive strategy to maintain stamina over time.",
        "prompt": "Daytime, natural daylight, soft light, wide shot, centered composition. Trump stands in a quiet side room, hands resting calmly, breathing steady as aides move subtly in the background."
    },
    {
        "narration": "Nutrition and routine adjustments are said to play a role in maintaining Trump’s current physical balance. Analysts note deliberate hydration, energy management, and structured pacing as integral components of daily routines.",
        "prompt": "Daytime, indoor daylight, soft light, medium close-up, centered composition. Trump lifts a glass of water, takes a controlled sip, then lowers it carefully onto a table."
    },
    {
        "narration": "These internal changes have largely remained invisible to the public eye. Observers note that careful backstage scheduling, quiet coordination, and subtle pacing preserve operational continuity while minimizing visible strain.",
        "prompt": "Daytime, diffuse daylight, soft light, mid shot, centered composition. Trump walks along a corridor, footsteps quiet, lighting evenly following his movement."
    },
    {
        "narration": "Staff coordination has become increasingly precise to avoid unnecessary delays or strain. Analysts note choreography-like timing, clear signaling, and deliberate staff positioning to preserve energy and ensure smooth transitions.",
        "prompt": "Daytime, daylight, soft light, wide shot, balanced composition. Trump follows a clear path marked by subtle cues as aides maintain positions at a distance."
    },
    {
        "narration": "Observers note a calmer, more deliberate rhythm to Trump’s behind-the-scenes activity. The measured approach appears designed to sustain consistent performance while reducing the likelihood of exhaustion during public sequences.",
        "prompt": "Daytime, natural daylight, soft light, mid shot, centered composition. Trump pauses briefly, adjusts his stance, then continues forward at a steady pace."
    },
    {
        "narration": "Supporters describe the changes as signs of controlled leadership adaptation over time. Advocates argue that structured pacing demonstrates experience, prudence, and a focus on effective stewardship rather than overstretching through extended public exposure.",
        "prompt": "Daytime, daylight, soft light, medium close-up, centered composition. Trump looks forward attentively, gives a slight nod, then turns his head toward the exit."
    },
    {
        "narration": "Taken together, daily routine adjustments reflect a broader effort to sustain long-term operational stability. Analysts see a pattern of measured engagement, strategic rest, and consistent public presence aligned with longevity goals.",
        "prompt": "Daytime, daylight, soft light, mid shot, centered composition. Trump exits an interior space calmly, movement smooth as the background activity gradually stills."
    },
    # chapter 6
    {
        "narration": "As the campaign calendar advances, Trump’s public schedule reflects deliberate compression, with fewer appearances clustered over shorter, carefully managed time frames. Observers note timing adjustments aimed at balancing visibility with recovery needs.",
        "prompt": "Daytime, natural daylight, soft light, mid shot, centered composition. Trump arrives at an event entrance, pauses to orient himself, then proceeds forward at a measured pace as staff indicate timing cues."
    },
    {
        "narration": "Event listings show increased gaps between engagements, suggesting intentional spacing designed to balance visibility with physical recovery. Analysts highlight the role of buffer periods in preserving stamina across demanding travel and appearance schedules.",
        "prompt": "Daytime, daylight through open space, soft light, wide shot, balanced composition. Trump transitions between locations, walking along a clearly defined route while the background gradually clears."
    },
    {
        "narration": "Campaign officials describe the adjustments as strategic planning rather than reaction to health concerns. Observers note that deliberate scheduling, route control, and limited walkabouts support consistent messaging while managing physical demands.",
        "prompt": "Daytime, indoor daylight, soft light, mid shot, centered composition. Trump stands beside aides, listens briefly, nods once, then signals forward movement."
    },
    {
        "narration": "Observers note that Trump now exits events promptly, limiting extended interaction periods that once characterized his appearances. This careful departure practice appears designed to prevent fatigue and preserve a predictable public tempo.",
        "prompt": "Daytime, natural daylight, soft light, medium-wide shot, centered composition. Trump concludes a brief stop, turns smoothly, and walks toward an exit as microphones lower."
    },
    {
        "narration": "Compared with earlier years, spontaneous stops and extended walkabouts have become increasingly rare. Analysts point to tighter routing, staff management, and deliberate pacing intended to maximize impact while minimizing physical exertion.",
        "prompt": "Daytime, daylight, soft light, mid shot, centered composition. Trump follows a straight path, steady steps emphasized while surrounding figures remain stationary."
    },
    {
        "narration": "Supporters argue the streamlined schedule reflects experience and efficiency acquired over decades of public life. Proponents say the focused approach enhances message delivery while conserving the principal's energy for high-priority engagements.",
        "prompt": "Daytime, natural daylight, soft light, medium close-up, centered composition. Trump maintains a composed posture, briefly acknowledging those ahead before continuing."
    },
    {
        "narration": "Critics counter that the reduced tempo underscores concerns about endurance at an advanced age. Observers debate whether visible pacing and fewer spontaneous interactions reflect strategic choices or limitations tied to stamina.",
        "prompt": "Daytime, daylight, soft light, mid shot, centered composition. Trump pauses momentarily, adjusts his footing, then resumes forward movement without haste."
    },
    {
        "narration": "Media analysis increasingly frames these patterns within broader discussions of aging leadership. Commentators connect observable scheduling and movement choices to ongoing debates about public expectations, energy, and the optics of age.",
        "prompt": "Daytime, diffuse daylight, soft light, wide shot, balanced composition. Trump moves through a press-lined corridor as cameras track his progression."
    },
    {
        "narration": "Despite speculation, no definitive medical explanation has been offered to clarify the scheduling changes. Observers emphasize the need for verified information even as visual patterns continue to shape public discourse and media narratives.",
        "prompt": "Daytime, indoor daylight, soft light, medium close-up, centered composition. Trump looks ahead, expression neutral, then shifts direction toward a side exit."
    },
    {
        "narration": "Ultimately, Trump’s condensed agenda stands as a visible symbol of how age, politics, and perception now intersect. Analysts observe a carefully curated public presence that balances continuity of leadership with practical energy management.",
        "prompt": "Daytime, natural daylight, soft light, mid shot, centered composition. Trump leaves the venue calmly, movement steady as the surrounding space gradually empties."
    }
]

token = '6A5AA1D4EAFF4E9FB37E23D68491D6F4'

def XTimestamp(): return datetime.datetime.now(datetime.timezone.utc).strftime('%a %b %d %Y %H:%M:%S GMT+0000 (Coordinated Universal Time)')

def sec_ms_gec():
    ticks = datetime.datetime.now(datetime.timezone.utc).timestamp()
    ticks += 11644473600
    ticks -= ticks % 300
    ticks *= 1e9 / 100
    str_to_hash = f'{ticks:.0f}' + token
    return hashlib.sha256(str_to_hash.encode()).hexdigest().upper()

#https://learn.microsoft.com/en-us/azure/ai-services/speech-service/language-support?tabs=tts
speak = lxml.etree.Element('speak', version='1.0', xmlns='http://www.w3.org/2001/10/synthesis', attrib={'{http://www.w3.org/XML/1998/namespace}lang':'en-US'})
voice = lxml.etree.SubElement(speak, 'voice', name='Microsoft Server Speech Text to Speech Voice (en-US, EmmaMultilingualNeural)')

async def edge(prompt):
    voice.text = prompt
    result = []
    userAgent = fake_useragent.UserAgent(platforms='desktop').edge
    async with aiohttp.ClientSession(headers={'user-agent':userAgent}) as client:
        async with client.ws_connect('wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1', params={'TrustedClientToken':token ,'ConnectionId':builtins.str(uuid.uuid4()).replace('-', ''), 'Sec-MS-GEC':sec_ms_gec(), 'Sec-MS-GEC-Version':'1-' + re.search(r'Chrome/([\d.]+)', userAgent).group(1)}) as websocket:
            message = email.message.EmailMessage(policy=email.policy.HTTP)
            message.add_header('X-Timestamp', XTimestamp())
            message.add_header('Content-Type', 'application/json; charset=utf-8')
            message.add_header('Path', 'speech.config')
            await websocket.send_str(message.as_string() + json.dumps({'context':{'synthesis':{'audio':{'outputFormat':'audio-24khz-48kbitrate-mono-mp3'}}}}))
            message = email.message.EmailMessage(policy=email.policy.HTTP)
            message.add_header('X-RequestId', builtins.str(uuid.uuid4()).replace('-', ''))
            message.add_header('Content-Type', 'application/ssml+xml')
            message.add_header('X-Timestamp', XTimestamp() + 'Z')  # This is not a mistake, Microsoft Edge bug.
            message.add_header('Path', 'ssml')
            await websocket.send_str(message.as_string() + lxml.etree.tostring(speak).decode())
            async for _ in websocket:
                if _.type == aiohttp.WSMsgType.TEXT:
                    if email.message_from_string(_.data).get('Path') == 'turn.end':break
                if _.type == aiohttp.WSMsgType.BINARY: result += _.data[builtins.int.from_bytes(_.data[:2]) + 2:],
    return b''.join(result)

async def google(prompt):
    async with aiohttp.ClientSession(headers={'user-agent':fake_useragent.UserAgent().chrome}) as client:
        async with client.get('https://translate.google.com/translate_tts', params={'ie':'UTF-8', 'q':prompt, 'tl':'en', 'client':'tw-ob'}) as _: return await _.content.read()

async def espeak(prompt):
    espeak = await asyncio.create_subprocess_exec('espeak-ng', '--stdout', '-v', 'en-us+f4', prompt, stdout=asyncio.subprocess.PIPE)
    return await espeak.stdout.read()

async def main():
    app = aiohttp.web.Application()
    app.add_routes([aiohttp.web.static('/', pathlib.Path(__file__).resolve().parent, show_index=True)])
    runner = aiohttp.web.AppRunner(app)
    await runner.setup()
    site = aiohttp.web.TCPSite(runner, port=7860)
    await site.start()
    async with aiohttp.ClientSession(headers={'authorization':'Bearer ' + os.getenv('modelscope')}, timeout=aiohttp.ClientTimeout()) as client:
        en = 'https://chaowenguo-en.ms.show/'
        async with client.post(urllib.parse.urljoin(en, 'imageStart'), json={'prompt':scripts[0].get('prompt'), 'height':720, 'width':1280}) as _:pass
        while True:
            async with client.get(urllib.parse.urljoin(en, 'imageGet')) as qwen:
                print(qwen.status)
                if qwen.status == 404: await asyncio.sleep(60)
                else:
                    buffer = io.BytesIO(await qwen.content.read())
                    image = PIL.Image.open(buffer)
                    with av.open('output.mp4', mode='w') as writer:
                        video = writer.add_stream('h264', rate=8)
                        video.height = image.size[1]
                        video.width = image.size[0]
                        video.pix_fmt = 'yuv420p'
                        videoPts = 0
                        audioPts = 0
                        audio = None
                        for index, (script, last) in builtins.enumerate(itertools.pairwise(scripts)):
                            outer = False
                            while True:
                                with aiohttp.MultipartWriter('form-data') as mpwriter:
                                    mpwriter.append(script.get('prompt')).set_content_disposition('form-data', name='prompt')
                                    mpwriter.append(last.get('prompt')).set_content_disposition('form-data', name='last')
                                    mpwriter.append(buffer.getvalue(), {'Content-Type':'image/png'}).set_content_disposition('form-data', name='image', filename='image.png')
                                    async with client.post(urllib.parse.urljoin(en, 'videoStart'), data=mpwriter) as _: pass
                                    while True:
                                        try:
                                            async with client.get(urllib.parse.urljoin(en, 'videoGet')) as get:
                                                print(get.status)
                                                match get.status:
                                                    case 404: await asyncio.sleep(60)
                                                    case 500 | 429: break
                                                    case 200:
                                                        reader = numpy.load(io.BytesIO(await get.content.read())).get('arr_0')
                                                        buffer.seek(0)
                                                        buffer.truncate(0)
                                                        PIL.Image.fromarray(reader[-1]).save(buffer, format='png')
                                                        with av.open(io.BytesIO(await sys.modules.get(__name__).espeak(script.get('narration'))), format='wav') as container:
                                                            if not audio: audio = writer.add_stream('aac', rate=container.streams.audio[0].rate)
                                                            speed = builtins.float(container.streams.audio[0].duration * container.streams.audio[0].time_base) / 10
                                                            print(speed)
                                                            graph = av.filter.Graph()
                                                            graph.link_nodes(graph.add_abuffer(template=container.streams.audio[0]), graph.add('atempo', builtins.str(speed)), graph.add('apad', 'whole_dur=10'), graph.add('atrim', '0:10'), graph.add('abuffersink')).configure()
                                                            frames = []
                                                            for frame in container.decode():
                                                                graph.push(frame)
                                                                while True:
                                                                    try: frames += graph.pull(),
                                                                    except (av.BlockingIOError, av.EOFError): break
                                                            for frame in frames:
                                                                frame.pts = audioPts
                                                                audioPts += frame.samples
                                                                writer.mux(audio.encode(frame))
                                                        graph = av.filter.Graph()
                                                        pathlib.Path(__file__).resolve().parent.joinpath('subtitle.ass').write_text(pathlib.Path(__file__).resolve().parent.joinpath('subtitle').read_text().replace('left', builtins.str(datetime.timedelta(seconds=index * 10))).replace('right', builtins.str(datetime.timedelta(seconds=(index + 1) * 10))).replace('prompt', script.get('narration')))
                                                        graph.link_nodes(graph.add_buffer(height=video.height, width=video.width, format='rgb24', time_base=video.time_base), graph.add('subtitles', 'subtitle.ass'), graph.add('buffersink')).configure()
                                                        for _ in itertools.islice(reader, reader.shape[0] - 1):
                                                            frame = av.VideoFrame.from_ndarray(_)
                                                            frame.pts = videoPts
                                                            videoPts += video.time_base.denominator // video.average_rate
                                                            graph.push(frame)
                                                            while True:
                                                                try: writer.mux(video.encode(graph.pull()))
                                                                except (av.BlockingIOError, av.EOFError):break
                                                        graph.push(None)
                                                        while True:
                                                            try: writer.mux(video.encode(graph.pull()))
                                                            except (av.BlockingIOError, av.EOFError):break
                                                        outer = True
                                                        break
                                        except (aiohttp.ClientConnectionError, aiohttp.ClientPayloadError): break
                                    if outer: break
                        writer.mux(video.encode())
                        writer.mux(audio.encode())
                    break
        output = pathlib.Path(__file__).resolve().parent.joinpath('output.mp4').read_bytes()
        #async with client.post('https://oauth2.googleapis.com/token', json={'client_id':os.getenv('youtubeId'), 'client_secret':os.getenv('youtubeSecret'), 'refresh_token':os.getenv('refresh'), 'grant_type':'refresh_token'}) as token: 
        #    accessToken = (await token.json()).get('access_token')
        #    async with client.post('https://www.googleapis.com/upload/youtube/v3/videos', params={'uploadType':'resumable', 'part':'snippet,status'}, headers={'authorization':'Bearer ' + accessToken, 'X-Upload-Content-Type':'video/mp4', 'X-Upload-Content-Length':builtins.str(builtins.len(output))}, json={'snippet':{'title':'gorgeous', 'description':'gorgeous', 'tags':['gorgeous'], 'categoryId': 22}, 'status':{'privacyStatus':'public', 'selfDeclaredMadeForKids':False}}) as metadata: # can not use metadata.url because the metadata.status == 200 not 301 or 302 aiohttp will not redirect
        #        async with client.post(metadata.headers.get('Location'), headers={'authorization':'Bearer ' + accessToken}, data=output) as upload:
        #            async with client.post('https://www.googleapis.com/youtube/v3/playlistItems', params={'part':'snippet'}, headers={'authorization':'Bearer ' + accessToken}, json={'snippet':{'playlistId':'PLREwfQq2HDLcuyUDf0d3_t7ZIFnz6tK1x', 'resourceId':{'kind':'youtube#video', 'videoId':(await upload.json()).get('id')}}}) as _: pass
        async with client.post('https://api.dailymotion.com/oauth/token', data={'grant_type':'password', 'client_id':os.getenv('dailymotionId'), 'client_secret':os.getenv('dailymotionSecret'), 'scope':'manage_videos', 'username':'bill8bush', 'password':os.getenv('password')}) as token:
            accessToken = (await token.json()).get('access_token')
            async with client.get('https://api.dailymotion.com/file/upload', headers={'authorization':'Bearer ' + accessToken}) as upload:
                with aiohttp.MultipartWriter('form-data') as mpwriter:
                    mpwriter.append(output, {'Content-Type':'video/mp4'}).set_content_disposition('form-data', name='file', filename='video.mp4')
                    async with client.post((await upload.json()).get('upload_url'), headers={'authorization':'Bearer ' + accessToken}, data=mpwriter) as url:
                        async with client.post('https://api.dailymotion.com/user/x3f9ing/videos', headers={'authorization':'Bearer ' + accessToken}, data={'url':(await url.json()).get('url'), 'title':'Dailymotion upload test', 'channel':'news', 'published':'true', 'private':'false', 'is_created_for_kids':'false', 'description':'abv'}) as _: pass #https://developers.dailymotion.com/reference/video-categories 
    HubApi().upload_file(path_or_fileobj='output.mp4', path_in_repo='en.mp4', repo_id='chaowenguo/wan', repo_type='dataset', token=os.getenv('modelscope'))
    await asyncio.sleep(math.inf)

try:
    uvloop.run(main())
except:
    pathlib.Path(__file__).resolve().parent.joinpath('en.txt').write_text(traceback.format_exc())
    huggingface_hub.upload_file(path_or_fileobj='en.txt', path_in_repo='en.txt', repo_id='exact-railcar/wan', repo_type='dataset', token=os.getenv('huggingface'))
    time.sleep(math.inf)  