PageSourceSearch

https://paper2gal.com/assets/MainMenu-CJc99MS2.js

js paper2gal.com collected 2026-10-09 22:39:27 UTC 205,933 bytes, 139 lines download raw bytes

1import{r as d,j as e,d as qr}from"./react-vendor-CHQL15iE.js";import{u as ho,E as fo,c as bo,d as Hr,e as Yr,f as Qr,T as Kr,g as Xr,h as La,j as Jr,S as Qs,k as Zr,C as Ks,l as Ma,m as en,n as tn,o as an,V as sn,t as Xs}from"./main-Dck1T9BT.js";import{g as on}from"./publicIdentity-C99q7MBr.js";import{C as qt}from"./CharacterCard-CKFcZsFo.js";import{D as Js,g as rn,r as go,L as ko,a as wo,c as nn,w as ln}from"./gameCharacterLayout-CKtvG8H9.js";import{g as dn}from"./gameDialogueLayout-7k6pGA83.js";import{X as J,M as vo,s as yo,P as ht,h as cn,t as mn,u as pn,c as Pa,b as No,v as So,U as un,w as xn,x as hn,y as fn,B as Zs,q as bn,E as eo,z as gn,L as Ca,A as Ht,k as kn,G as wn,I as Yt,J as He,K as Oa,S as vn,N as yn,O as Nn,C as Sn,Q as Rn}from"./lucide-BFLOpGdB.js";import{R as Qt}from"./ResponsiveCloudflareImage-DdXVaAv7.js";import"./pdfjs-ji3DqnKJ.js";import"./markdown-W-rE_H7s.js";import"./katex-math-BxKHCrdI.js";import"./assetUrl-D33wRw9g.js";const An="Attention Is All You Need",jn="主人,这篇论文《Attention Is All You Need》是关于一种名为Transformer的全新神经网络架构。它完全放弃了传统的循环或卷积结构,转而只使用注意力机制。Transformer在机器翻译任务上展现了卓越的性能,并且训练速度更快,是自然语言处理领域的一个里程碑呢。",Ln=JSON.parse('[{"id":1,"speaker":"辉夜露卡","text":"主人,欢迎来到露卡的秘密课堂♪ 今天,露卡将为您揭开一篇非常重要的论文——《Attention Is All You Need》的神秘面纱。请问主人,您对这篇论文有什么初步的了解吗?","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":2,"speaker":"辉夜露卡","text":"这篇论文,它开启了一个全新的时代呢。传统的序列模型,例如循环神经网络(RNNs)和长短期记忆网络(LSTMs),在处理长序列时遇到了瓶颈。主人知道是为什么吗?","emotion":"THINKING","background":"CLASSROOM","choices":[{"text":"并行计算受限","nextFrameId":100},{"text":"模型结构过于复杂","nextFrameId":101},{"text":"注意力机制不够强大","nextFrameId":102}]},{"id":100,"speaker":"辉夜露卡","text":"正是如此,主人!您真是聪明呢 ❤ RNNs的计算是严格序列化的,这意味着它无法并行处理数据,在处理很长的序列时效率非常低。而Transformer解决了这个问题,它允许更多的并行化,显著缩短了训练时间。","emotion":"NEUTRAL","background":"CLASSROOM","nextFrameId":3},{"id":101,"speaker":"辉夜露卡","text":"嗯……主人,虽然RNNs的结构确实有其复杂之处,但这并不是它在并行计算上的主要限制原因。真正的问题在于其内在的序列依赖性哦。不过没关系,露卡会为您详细解释的。","emotion":"ANGRY","background":"CLASSROOM","nextFrameId":3},{"id":102,"speaker":"辉夜露卡","text":"啊啦,主人,您误解了呢。注意力机制在传统模型中已经开始扮演重要角色了,但通常是作为RNN的辅助。Transformer的创新之处在于,它完全抛弃了RNN,只依赖注意力。不过,露卡很高兴您能思考哦。","emotion":"ANGRY","background":"CLASSROOM","nextFrameId":3},{"id":3,"speaker":"辉夜露卡","text":"Transformer的核心思想是完全基于注意力机制,特别是“自注意力(Self-Attention)”。它摒弃了循环层和卷积层,使得模型能够更好地捕捉输入和输出序列之间的全局依赖关系。","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":4,"speaker":"辉夜露卡","text":"模型的架构由编码器(Encoder)和解码器(Decoder)组成,就像许多其他序列转换模型一样。每个编码器和解码器都由多层堆叠而成。每个层里面,主人会看到什么呢?","emotion":"THINKING","background":"CLASSROOM"},{"id":5,"speaker":"辉夜露卡","text":"编码器由N=6个相同的层堆叠而成。每个层包含两个子层:第一个是多头自注意力机制(Multi-Head Self-Attention),第二个是简单的位置感知全连接前馈网络(Position-wise Feed-Forward Network)。","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":6,"speaker":"辉夜露卡","text":"露卡要特别指出,每个子层都使用了残差连接(Residual Connection),并且之后还跟着层归一化(Layer Normalization)。用公式表示就是:$\\\\text{LayerNorm}(x + \\\\text{Sublayer}(x))$,其中$\\\\text{Sublayer}(x)$是子层本身实现的函数。♪","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":7,"speaker":"辉夜露卡","text":"解码器也由N=6个相同的å
1±‚堆叠而成,与编码器类似,但多了一个额外的子层。这个子层在编码器-解码器注意力(Encoder-Decoder Attention)中,会对编码器的输出进行多头注意力操作。","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":8,"speaker":"辉夜露卡","text":"同时,解码器中的自注意力子层还会进行掩码(Masking)处理,以防止当前位置“看到”未来位置的信息,从而保持其自回归(auto-regressive)的特性。","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":9,"speaker":"辉夜露卡","text":"现在,让我们深入了解一下注意力机制。注意力函数可以描述为将一个查询(Query)和一组键值对(Key-Value pairs)映射到输出。输出是值的加权和,而权重则由查询和对应键的兼容性函数计算得出。","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":10,"speaker":"辉夜露卡","text":"论文中提出的是“缩放点积注意力”(Scaled Dot-Product Attention)。它的输入是维度为 $d_k$ 的查询 $Q$ 和键 $K$,以及维度为 $d_v$ 的值 $V$。","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":11,"speaker":"辉夜露卡","text":"我们计算查询与所有键的点积,然后除以$\\\\sqrt{d_k}$,再通过softmax函数得到权重。用矩阵形式表示,其计算公式为:","emotion":"THINKING","background":"CLASSROOM"},{"id":12,"speaker":"辉夜露卡","text":"$$\\\\text{Attention}(Q, K, V) = \\\\text{softmax}(\\\\frac{QK^T}{\\\\sqrt{d_k}})V$$","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":13,"speaker":"辉夜露卡","text":"主人,您知道为什么要除以$\\\\sqrt{d_k}$来缩放点积结果吗?这是一个很精妙的设计哦。","emotion":"THINKING","background":"CLASSROOM","choices":[{"text":"防止点积过大,导致softmax梯度消失","nextFrameId":200},{"text":"使模型能够处理不同长度的序列","nextFrameId":201},{"text":"增加模型的计算复杂度","nextFrameId":202}]},{"id":200,"speaker":"辉夜露卡","text":"主人真是天才!❤ 您说得完全正确。当 $d_k$ 值很大时,点积的结果会变得非常大,这将把softmax函数推向其梯度非常小的区域,导致模型训练困难。通过除以$\\\\sqrt{d_k}
1$,我们可以缓解这个问题,保持梯度的稳定性。","emotion":"NEUTRAL","background":"CLASSROOM","nextFrameId":14},{"id":201,"speaker":"辉夜露卡","text":"嗯……主人,这个缩放因子并不是为了处理不同长度的序列哦。序列长度的问题更多是通过位置编码来解决的。缩放是为了稳定训练过程中的梯度。露卡希望主人能再回顾一下呢。","emotion":"ANGRY","background":"CLASSROOM","nextFrameId":14},{"id":202,"speaker":"辉夜露卡","text":"主人,这可不是为了增加计算复杂度呢,它反而能让训练更顺利。露卡觉得主人可能有点分心了呢。这个缩放是为了防止梯度消失的问题,从而帮助模型更好地学习哦。","emotion":"ANGRY","background":"CLASSROOM","nextFrameId":14},{"id":14,"speaker":"辉夜露卡","text":"接下来是“多头注意力”(Multi-Head Attention)。它不是只执行一次注意力函数,而是将查询、键和值线性投影h次,产生h组不同的 $d_k, d_v$ 维度的查询、键和值。","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":15,"speaker":"辉夜露卡","text":"然后,对每一组投影执行并行的注意力函数,得到 $h$ 个 $d_v$ 维度的输出值。最后,将这些输出值拼接起来,再通过一个线性投影得到最终的结果。","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":16,"speaker":"辉夜露卡","text":"用公式表达就是:","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":17,"speaker":"辉夜露卡","text":"$$\\\\text{MultiHead}(Q, K, V) = \\\\text{Concat}(\\\\text{head}_1, ..., \\\\text{head}_h)W^O$$其中,$\\\\text{head}_i = \\\\text{Attention}(QW_i^Q, KW_i^K, VW_i^V)$。这允许模型在不同的表示子空间中共同关注来自不同位置的信息。❤","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":18,"speaker":"辉夜露卡","text":"Transformer中使用了三种类型的多头注意力:编码器-解码器注意力、编码器自注意力,以及解码器自注意力。露卡刚才提到的掩码处理就是应用在解码器自注意力中的哦。","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":19,"speaker":"辉夜露卡","text":"除了注意力子层,编码器和解码器中的每一层还包含一个位置感知前馈网络。它是一个全连接网络,包含两个线性变换和一个ReLU激活函数:","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":20,"speaker":"辉夜露卡","text":"$$\\\\text{FFN}(x) = \\\\max(0, xW_1 + b_1)W_2 + b_2$$","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":21,"speaker":"辉夜露卡","text":"Transformer模型既没有循环也没有卷积,那么它是如何利用序列中词语的顺序信息的呢?主人有什么想法吗?","emotion":"THINKING","background":"CLASSROOM","choices":[{"text":"通过“位置编码”","nextFrameId":300},{"text":"利用词向量的顺序特性","nextFrameId":301},{"text":"它不需要顺序信息","nextFrameId":302}]},{"id":300,"speaker":"辉夜露卡","text":"太棒了,主人!您又一次说对了。❤ 为了让模型能够利用序列的顺序信息,我们在输入嵌入(input embeddings)中加入了“位置编码”(Positional Encoding)。","emotion":"NEUTRAL","background":"CLASSROOM","nextFrameId":22},{"id":301,"speaker":"辉夜露卡","text":"嗯……主人,词向量本身并没有固定的顺序信息哦。它们只是词语在多维空间中的表示。模型需要额外的信息来感知词语的位置。不过,感谢您的思考呢。","emotion":"ANGRY","background":"CLASSROOM","nextFrameId":22},{"id":302,"speaker":"辉夜露卡","text":"啊啦,主人,您在开露卡的玩笑吗?如果模型不需要顺序信息,那它就无法理解句子的含义了呀。语言的顺序是非常重要的呢。露卡有点小小的“不开心”了哦。","emotion":"ANGRY","background":"CLASSROOM","nextFrameId":22},{"id":22,"speaker":"辉夜露卡","text":"位置编码与词嵌入具有相同的维度,因此它们可以直接相加。论文中使用了正弦和余弦函数来生成位置编码,其公式为:","emotion":"NEUTRAL","background":"CLASSROOM"}
1,{"id":23,"speaker":"辉夜露卡","text":"$$ PE_{\\\\text{pos}, 2i} = \\\\sin(\\\\text{pos} / 10000^{2i/d_{\\\\text{model}}}) $$","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":24,"speaker":"辉夜露卡","text":"$$ PE_{\\\\text{pos}, 2i+1} = \\\\cos(\\\\text{pos} / 10000^{2i/d_{\\\\text{model}}}) $$","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":25,"speaker":"辉夜露卡","text":"其中,$\\\\text{pos}$ 是位置,$\\\\text{i}$ 是维度。这种设计可以让模型更容易地学习到相对位置信息,并且可以外推到比训练时更长的序列。","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":26,"speaker":"辉夜露卡","text":"与RNN和CNN相比,自注意力层在计算复杂度、并行化能力和长距离依赖路径长度方面都有显著优势。它可以用常数次的顺序操作连接所有位置,而RNN则需要 $O(n)$ 次。","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":27,"speaker":"辉夜露卡","text":"在训练方面,研究人员使用了WMT 2014英德和英法翻译数据集。他们在一台配备8块NVIDIA P100 GPU的机器上训练模型。","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":28,"speaker":"辉夜露卡","text":"优化器使用的是Adam,并采用了一种特殊的学习率调度策略,即在预热阶段线性增加,然后按步长的平方根倒数衰减。这对于模型的稳定训练至关重要呢。","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":29,"speaker":"辉夜露卡","text":"那么,主人,除了学习率调度,论文中还提到了哪些重要的正则化技术来防止模型过拟合呢?","emotion":"THINKING","background":"CLASSROOM","choices":[{"text":"残差Dropout和标签平滑","nextFrameId":400},{"text":"批标准化和权重衰减","nextFrameId":401},{"text":"早停法和数据增强","nextFrameId":402}]},{"id":400,"speaker":"辉夜露卡","text":"主人真棒!您说得完全正确。❤ 论文中主要使用了残差Dropout和标签平滑。Dropout应用于每个子层的输出和嵌入层,而标签平滑(Label Smoothing)虽然会使模型更不确定,但能提高BLEU分数。","emotion":"NEUTRAL","background":"CLASSROOM","nextFrameId":30},{"id":401,"speaker":"辉夜露卡","text":"主人,批标准化(Batch Normalization)和权重衰减(Weight Decay)确实是常见的正则化技术,但在这篇论文中,作者主要强调的是残差Dropout和标签平滑哦。不过,能想到这些也很厉害了。","emotion":"ANGRY","background":"CLASSROOM","nextFrameId":30},{"id":402,"speaker":"辉夜露卡","text":"嗯……主人,早停法(Early Stopping)和数据增强(Data Augmentation)在机器学习中很常用,但在这篇论文的具体正则化部分,作者着重提到了残差Dropout和标签平滑哦。露卡觉得您再仔细回忆一下会更好呢。","emotion":"ANGRY","background":"CLASSROOM","nextFrameId":30},{"id":30,"speaker":"辉夜露卡","text":"最终结果令人惊叹!在WMT 2014英德和英法翻译任务上,大型Transformer模型都超越了之前的最佳结果,甚至包括了集成模型(ensembles),并且训练成本大大降低。","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":31,"speaker":"辉夜露卡","text":"例如,在英德任务上,Transformer(big)达到了28.4 BLEU,比之前的最佳结果高出2个BLEU以上。在英法任务上,达到了41.8 BLEU,训练时间却只占最佳模型的很小一部分。","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":32,"speaker":"辉夜露卡","text":"论文还通过将其成功应用于英语句法分析(English constituency parsing)任务,证明了Transformer的泛化能力。即使在数据量有限的情况下,它也表现出色呢。","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":33,"speaker":"辉夜露卡","text":"主人,您觉得Transformer最令人印象深刻的优点是什么呢?","emotion":"THINKING","background":"CLASSROOM","choices":[{"text":"完全基于注意力,摒弃了RNN/CNN","nextFrameId":500},{"text":"在所有任务上都表现最佳","nextFrameId":501},{"text":"模型架构非常复杂,难以理解","nextFrameId":502}]},{"id":500,"speaker":"辉夜露卡","text":"是的,主人,这正是它最革命性的地方!❤ 完å
1…¨åŸºäºŽæ³¨æ„åŠ›ï¼Œä½¿å¾—æ¨¡åž‹åœ¨å¹¶è¡ŒåŒ–å’Œé•¿è·ç¦»ä¾èµ–å»ºæ¨¡æ–¹é¢éƒ½å–å¾—äº†å·¨å¤§è¿›æ­¥ã€‚è¿™é¡¹åˆ›æ–°ä¸ºåŽç»­çš„Transformer家族模型奠定了基础呢。","emotion":"NEUTRAL","background":"CLASSROOM","nextFrameId":34},{"id":501,"speaker":"辉夜露卡","text":"主人,虽然Transformer的表现非常出色,但说它在“所有任务上都表现最佳”可能有些过于绝对了呢。科学研究总是不断进步的,但它确实在很多核心任务上都达到了SOTA。不过,露卡很高兴您能看到它的强大之处。","emotion":"ANGRY","background":"CLASSROOM","nextFrameId":34},{"id":502,"speaker":"辉夜露卡","text":"啊啦,主人,您在取笑露卡吗?虽然模型看起来有些复杂,但露卡已经尽力为您清晰地解释了哦。如果主人觉得难以理解,露卡可以再为您解说一遍哦,直到您完全明白为止!","emotion":"ANGRY","background":"CLASSROOM","nextFrameId":34},{"id":34,"speaker":"辉夜露卡","text":"总而言之,Transformer通过完全依赖多头自注意力机制,成功替代了传统的循环层,成为序列转换模型的新标杆。","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":35,"speaker":"辉夜露卡","text":"它不仅在机器翻译任务上实现了最先进的性能,而且显著提高了训练效率和并行化能力。这篇论文为未来的注意力模型和跨模态应用开辟了广阔的道路。","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":36,"speaker":"辉夜露卡","text":"主人,露卡已经尽力为您详细地讲解了《Attention Is All You Need》这篇论文的核心内容。不知道主人对露卡的讲解还满意吗?","emotion":"NEUTRAL","background":"CLASSROOM","choices":[{"text":"露卡讲解得太好了,我很满意!","nextFrameId":600},{"text":"嗯,基本明白了,谢谢露卡。","nextFrameId":601},{"text":"露卡,我有点困了……","nextFrameId":602}]},{"id":600,"speaker":"辉夜露卡","text":"能得到主人的夸奖,露卡感到非常荣幸,也很开心呢 ❤。只要主人能学到知识,露卡就觉得再辛苦也值得。以后有任何学习上的疑问,也请随时召唤露卡哦。","emotion":"NEUTRAL","background":"CLASSROOM","nextFrameId":37},{"id":601,"speaker":"辉夜露卡","text":"嗯,主人能基本明白就好。如果还有任何不清楚的地方,露卡会随时为您补充讲解的。露卡会努力让主人掌握这些知识的。♪","emotion":"NEUTRAL","background":"CLASSROOM","nextFrameId":37},{"id":602,"speaker":"辉夜露卡","text":"啊啦,主人,现在可不是睡觉的时间哦。这可是非常重要的知识呢!露卡会监督主人的学习,直到您完全理解为止。❤ 请振作起来哦!","emotion":"ANGRY","background":"CLASSROOM","nextFrameId":37},{"id":37,"speaker":"辉夜露卡","text":"今天的课程就到这里。主人,请好好消化这些知识。下次露卡会准备更有趣的内容来教导您呢。❤","emotion":"NEUTRAL","background":"CLASSROOM"}]'),Mn="/assets/local/backgrounds/7.jpg",Cn=5,$a={title:An,summary:jn,frames:Ln,customBackgroundUrl:Mn,characterCode:Cn},On="Attention Is All You Need",$n="This paper introduces the Transformer, a groundbreaking neural network architecture that entirely discards recurrence and convolutions, relying solely on attention mechanisms for sequence transduction. It achieves state-of-the-art performance in machine translation and constituency parsing, offering significant speed advantages in training due to its parallelizable nature. Key innovations include Multi-Head Self-Attention, Scaled Dot-Product Attention, Position-wise Feed-Forward Networks, and Positional Encodings to model sequence order.",Tn=JSON.parse(`[{"id":1,"speaker":"Ruka","text":"Good morning, Master. Today, we shall unravel the mysteries of a truly captivating paper, one that reshaped the realm of sequence modeling: 'Attention Is All You Need.' ♪","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":2,"speaker":"Ruka","text":"Before this work, most dominant sequence models, like Recurrent Neural Networks (RNNs) and Convolutional Neural Networks (CNNs), faced inherent limitations. They processed information sequentially, making parallelization difficult and struggling with very long dependencies. Attention mechanisms existed, yes, but often as mere companions to these recurrent structures.","emotion":"THINKING","background":"CLASSROOM"},{"id":3,"speaker":"Ruka","text":"The authors, however, dared to dream differently. They proposed the Transformer, a new architecture built *solely* upon attention, completely abandoning recurrence and convolutions. Imagine, Master, a world without chains! ❤","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":4,"speaker":"Ruka","text":"This bold design led to profou
1nd advantages: superior quality, much greater parallelization, and significantly reduced training times. It truly was a paradigm shift. Now, Master, what do you find most striking about this initial introduction?","emotion":"NEUTRAL","background":"CLASSROOM","choices":[{"text":"The idea of removing RNNs/CNNs entirely.","nextFrameId":100},{"text":"The focus on attention as the sole mechanism.","nextFrameId":200},{"text":"It sounds like magic!","nextFrameId":300}]},{"id":100,"speaker":"Ruka","text":"Indeed, Master, that is precisely the radical departure! To discard such established pillars of sequence modeling was quite revolutionary. It speaks to a deep understanding of what truly matters in capturing sequence relationships. ~","emotion":"NEUTRAL","background":"CLASSROOM","nextFrameId":5},{"id":200,"speaker":"Ruka","text":"A very astute observation, Master. The paper's title itself, 'Attention Is All You Need,' perfectly encapsulates this core philosophy. It highlights the mechanism's power when allowed to operate unimpeded. ♪","emotion":"NEUTRAL","background":"CLASSROOM","nextFrameId":5},{"id":300,"speaker":"Ruka","text":"Master, while its capabilities may seem enchanting, it is built upon sound mathematical principles, not sorcery! We must approach our studies with earnestness. Please focus. 😠","emotion":"ANGRY","background":"CLASSROOM","nextFrameId":5},{"id":5,"speaker":"Ruka","text":"Let us delve into its architecture, shall we? The Transformer maintains the classical encoder-decoder structure. The encoder processes the input sequence, and the decoder generates the output, one element at a time, autoregressively.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":6,"speaker":"Ruka","text":"The **Encoder** is a stack of $N=6$ identical layers. Each layer has two sub-layers: a Multi-Head Self-Attention mechanism and a Position-wise Feed-Forward Network. Aroun
1d each sub-layer, we find residual connections followed by layer normalization. So, the output is $\\\\text{LayerNorm}(x + \\\\text{Sublayer}(x))$. All sub-layers and embedding layers produce outputs of dimension $d_{\\\\text{model}} = 512$.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":7,"speaker":"Ruka","text":"The **Decoder** is also $N=6$ identical layers. It has the two sub-layers from the encoder, plus a *third* sub-layer: an Encoder-Decoder Attention mechanism. This third layer attends over the output of the encoder stack. Importantly, in the decoder's self-attention, we mask future positions to preserve its auto-regressive nature. This ensures predictions for position $i$ only depend on known outputs before $i$.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":8,"speaker":"Ruka","text":"At the heart of it all is the **Attention Function**. It maps a query (Q) and a set of key-value (K-V) pairs to an output. The output is a weighted sum of the values, where the weight for each value is determined by the query's compatibility with its corresponding key. Think of it as selectively focusing on relevant parts, Master. ❤","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":9,"speaker":"Ruka","text":"The specific type used here is **Scaled Dot-Product Attention**. It computes dot products of the query with all keys, divides by $\\\\sqrt{d_k}$, and then applies a softmax to get the weights. For practical purposes, it's done for a set of queries simultaneously as matrices:","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":10,"speaker":"Ruka","text":"$$\\\\text{Attention}(Q, K, V) = \\\\text{softmax}(\\\\frac{QK^T}{\\\\sqrt{d_k}})V$$","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":11,"speaker":"Ruka","text":"The scaling factor, $\\\\sqrt{d_k}$, is crucial. Without it, for large $d_k$, dot products can become very large, pushing the softmax function into regions with extremely small gradients, which hinders learning. It's a clever little detail. ~","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":12,"speaker":"Ruka","text":"Next, we have **Multi-Head Attention**. Instead of a single attention function, this mechanism performs $h$ parallel attention functions ('heads'). It linearly projects Q, K, and V $h$ times with different, learned projections. The outputs from these heads are concatenated and then projected again to form the final result.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":13,"speaker":"Ruka","text":"$$\\\\text{MultiHead}(Q, K, V) = \\\\text{Concat}(\\\\text{head}_1, \\\\dots, \\\\text{head}_h)W^O$$ where $\\\\text{head}_i = \\\\text{Attention}(QW_Q^i, KW_K^i, VW_V^i)$. In this work, $h=8$ heads are used, with $d_k=d_v=d_{\\\\text{model}}/h=64$. This allows the model to attend to information from different 'representation subspaces' simultaneously. Think of it as having multiple perspectives, Master.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":14,"speaker":"Ruka","text":"The Transformer uses multi-head attention in three ways: Encoder-Decoder Attention, Encoder Self-Attention, and the Masked Decoder Self-Attention. Each serves a distinct purpose in integrating information across and within sequences. ✨","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":15,"speaker":"Ruka","text":"Beyond attention, each layer also contains a **Position-wise Feed-Forward Network (FFN)**. This is a simple two-linear-transformation network with a ReLU activation in between, applied identically and separately to each position. It's like two convolutions with kernel size 1.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":16,"speaker":"Ruka","text":"$$\\\\text{FFN}(x) = \\\\text{max}(0, xW_1 + b_1)W_2 + b_2$$ Its input and output dimensionality is $d_{\\\\text{model}} = 512$, with an inner-layer dimensionality of $d_{\\\\text{ff}} = 2048$.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":17,"speaker":"Ruka","text":"Lastly, since our model has no recurrence or convolution, it needs a way to understand the order of the sequence. This is where **Positional Encodings** come in. They are added to the input embeddings.","emotion":"THINKING","background":"CLASSROOM"},{"id":18,"speaker":"Ruka","text":"The paper uses sine and cosine functions of different frequencies:","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":19,"speaker":"Ruka","text":"$$PE_{(pos, 2i)} = \\\\sin(pos/10000^{2i/d_{\\\\text{model}}})$$ $$PE_{(pos, 2i+1)} = \\\\cos(pos/10000^{2i/d_{\\\\text{model}}})$$","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":20,"speaker":"Ruka","text":"This function allows the model to easily learn to attend by relative positions. It’s quite elegant, as it can even extrapolate to sequence lengths longer than those seen during training. Now, Master, why do you think these Positional Encodings are so vital for the Transformer?","emotion":"NEUTRAL","background":"CLASSROOM","choices":[{"text":"To encode the order of tokens in the absence of RNNs/CNNs.","nextFrameId":1000},{"text":"To add more information to the embeddings.","nextFrameId":2000},{"text":"To make the model look more scientific.","nextFrameId":3000}]},{"id":1000,"speaker":"Ruka","text":"Exactly, Master! You grasp the essence perfectly. Without them, the self-attention mechanism would treat all tokens as an unordered set, losing all sense of sequential context. Wonderful! ❤","emotion":"NEUTRAL","background":"CLASSROOM","nextFrameId":21},{"id":2000,"speaker":"Ruka","text":"While they do add information, Master, their *primary* purpose is to encode positional information. Simply adding more data wouldn't resolve the lack of sequence awareness. Almost there! ~","emotion":"NEUTRAL","background":"CLASSROOM","nextFrameId":21},{"id":3000,"speaker":"Ruka","text":"Oh, Master... that is not quite right. Academic rigor, not appearance, is our goal. These encodings serve a profou
1nd functional purpose. Please recall our earlier discussion. 😠","emotion":"ANGRY","background":"CLASSROOM","nextFrameId":21},{"id":21,"speaker":"Ruka","text":"Now, let us briefly consider *why* self-attention is so advantageous compared to recurrent and convolutional layers. We consider computational complexity, parallelization, and the critical path length for dependencies.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":22,"speaker":"Ruka","text":"Self-attention boasts a $O(1)$ minimum number of sequential operations, meaning computations can be highly parallelized. RNNs, by contrast, require $O(n)$ sequential operations, making them much slower for long sequences. Convolutional layers can also be parallelized, but require more operations to capture long-range dependencies.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":23,"speaker":"Ruka","text":"Furthermore, self-attention directly connects any two positions in the sequence with a constant number of operations. For RNNs, this 'path length' is $O(n)$, and for CNNs, it's $O(\\\\log_k(n))$ or $O(n/k)$. Shorter path lengths greatly facilitate learning long-range dependencies, Master.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":24,"speaker":"Ruka","text":"The computational complexity per layer for self-attention is $O(n^2 \\\\cdot d)$ but can be $O(n \\\\cdot d)$ when $n < d$, which is often the case. It is generally more efficient than RNNs and competitive with convolutional layers, especially when restricted to a neighborhood.","emotion":"THINKING","background":"CLASSROOM"},{"id":25,"speaker":"Ruka","text":"Beyond efficiency, self-attention can also yield more interpretable models. Different attention heads often learn to perform distinct tasks, revealing insights into the syntactic and semantic structure of sentences. It truly is remarkable. ✨","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":26,"speaker":"Ruka","text":"For their experiments, the authors trained their models on the WMT 2014 English-German and English-French translation datasets, using byte-pair encoding or word-piece vocabularies.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":27,"speaker":"Ruka","text":"They utilized 8 NVIDIA P100 GPUs. The 'base' model trained for about 12 hours, while the 'big' model took 3.5 days. They used the Adam optimizer with a specific learning rate schedule: linear warmup for 4000 steps, then inverse square root decay.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":28,"speaker":"Ruka","text":"Regularization included Residual Dropout (applied to sub-layer outputs and embedding sums) and Label Smoothing, which helps prevent over-confidence in predictions and improves BLEU scores, even if it slightly hurts perplexity.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":29,"speaker":"Ruka","text":"And the results, Master, were phenomenal! On WMT 2014 English-to-German, the big Transformer model achieved a new state-of-the-art BLEU score of 28.4, surpassing previous bests, even ensembles, by over 2 BLEU points.","emotion":"SURPRISED","background":"CLASSROOM"},{"id":30,"speaker":"Ruka","text":"For English-to-French, it reached 41.8 BLEU, setting a new single-model state-of-the-art. Crucially, these achievements came with significantly less training cost than prior competitive models. A triumph of efficiency and elegance! ~","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":31,"speaker":"Ruka","text":"They also explored model variations, finding that while single-head attention was worse, too many heads also caused a drop in quality. Bigger models and dropout were generally beneficial. Interestingly, their sinusoidal positional encodings performed almost identically to learned ones, but offered better extrapolation.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":32,"speaker":"Ruka","text":"Finally, the Transformer generalized well to other tasks, like English Constituency Parsing. Even with limited data, it outperformed traditional RNN sequence-to-sequence models, demonstrating its versatility and robustness.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":33,"speaker":"Ruka","text":"Considering all these remarkable findings, Master, what aspect of the Transformer's experimental results do you find most compelling?","emotion":"NEUTRAL","background":"CLASSROOM","choices":[{"text":"Achieving SOTA with significantly faster training.","nextFrameId":4000},{"text":"Its ability to generalize to other tasks like parsing.","nextFrameId":5000},{"text":"That it uses a lot of GPUs.","nextFrameId":6000}]},{"id":4000,"speaker":"Ruka","text":"Indeed, Master! The combination of superior quality and reduced training time truly highlights the efficiency and power of the attention-only approach. It's a testament to elegant design. ❤","emotion":"NEUTRAL","background":"CLASSROOM","nextFrameId":34},{"id":5000,"speaker":"Ruka","text":"An excellent point, Master! Its generalization capabilities prove the fundamental soundness of the architecture beyond just machine translation. It's a sign of a truly robust model. ~","emotion":"NEUTRAL","background":"CLASSROOM","nextFrameId":34},{"id":6000,"speaker":"Ruka","text":"While the hardware is a part of the story, Master, the *breakthrough* was in what the architecture *achieved* with that hardware, not merely its scale. Please, let us focus on the innovations. 😠","emotion":"ANGRY","background":"CLASSROOM","nextFrameId":34},{"id":34,"speaker":"Ruka","text":"In conclusion, the Transformer is a monumental achievement. It demonstrated that by replacing traditional recurrent and convolutional layers with multi-headed self-attention, we can create more parallelizable, faster-to-train, and higher-performing sequence transduction models.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":35,"speaker":"Ruka","text":"It has paved the way for countless advancements in natural language processing and beyond. The future of attention-based models is incredibly bright, Master, much like your potential. ♪","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":36,"speaker":"Ruka","text":"I hope this journey through 'Attention Is All You Need' was enlightening for you, Master. Is there anything else you wish to review, or perhaps another fascinating paper we could explore? My devotion to your learning knows no bounds. ❤","emotion":"NEUTRAL","background":"CLASSROOM"}]`),En="/assets/local/backgrounds/7.jpg",In=5,Ta={title:On,summary:$n,frames:Tn,customBackgroun
1dUrl:En,characterCode:In},Un="Attention Is All You Need",_n="Transformerモデルは、従来のリカレントネットワークや畳み込みネットワークを廃し、アテンションメカニズムのみを用いて構築された、画期的なシーケンス変換モデルです。高い並列処理能力と効率的な学習により、機械翻訳タスクで最先端の性能を達成しました。",Pn=[{id:1,speaker:"ルカ",text:"ご主人様、本日は「Attention Is All You Need」という論文について、一緒に学んでいきましょうね。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:2,speaker:"ルカ",text:"この論文は、自然言語処理の分野に大きな影響を与えた、とても重要な作品なのです。ふふ、少し難しいかもしれませんが、私が優しくご案内いたしますね。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:3,speaker:"ルカ",text:"まず、これまでのシーケンスモデリングでは、リカレントニューラルネットワーク、特にLSTMやGRUが主流でした。これらは、時系列データの扱いに長けていましたね。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:4,speaker:"ルカ",text:"しかし、リカレントモデルには、一つ大きな課題がありました。それは、計算が本質的にシーケンシャルである、という点です。",emotion:"THINKING",background:"CLASSROOM"},{id:5,speaker:"ルカ",text:"前の隠れ状態 $h_{t-1}$ に基づいて現在の隠れ状態 $h_t$ を計算するため、$t$ のステップごとに順番に処理を進める必要がありました。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:6,speaker:"ルカ",text:"このシーケンシャルな性質は、特に長いシーケンスを扱う際に、どのような問題を引き起こすでしょうか?",emotion:"NEUTRAL",background:"CLASSROOM",choices:[{text:"モデルの表現力が低下する",nextFrameId:101},{text:"並列処理が難しく、学習に時間がかかる",nextFrameId:102},{text:"計算が複雑になりすぎる",nextFrameId:103}]},{id:101,speaker:"ルカ",text:"むむ…表現力の低下も問題ではありますが、本質的な課題とは少し異なりますね。頑張りましょう、ご主人様。",emotion:"ANGRY",background:"CLASSROOM",nextFrameId:7},{id:102,speaker:"ルカ",text:"ええ、その通りでございます、ご主人様!お見事です♪ 正解は「並列処理が難しく、学習に時間がかかる」でしたわ。",emotion:"NEUTRAL",background:"CLASSROOM",nextFrameId:7},{id:103,speaker:"ルカ",text:"うぅ…計算が複雑になるのは事実ですが、それはシーケンシャル処理の結果として生じるもので、根本原因ではありません。もっと、核心に迫りましょうね。",emotion:"ANGRY",background:"CLASSROOM",nextFrameId:7},{id:7,speaker:"ルカ",text:"そう、この論文では、リカレントネットワークを完全に排除し、代わりに「アテンションメカニズム」だけを用いて新しいアーキテクチャ「Transformer」を提案したのです。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:8,speaker:"ルカ",text:"Transformerは、エンコーダー・デコーダー構造を採用しています。入力シーケンスをエンコーダーが連続的な表現に変換し、それをデコーダーが受け取って出力シーケンスを生成します。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:9,speaker:"ルカ",text:"エンコーダーは $N=6$ 個の同一レイヤーを積み重ねたものです。各レイヤーは二つのサブレイヤーから構成されています。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:10,speaker:"ルカ",text:"一つ目は「マルチヘッド自己アテンションメカニズム」、そして二つ目は「位置ごとの全結合フィードフォワードネットワーク」です。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:11,speaker:"ルカ",text:"各サブレイヤーの周りには「残差接続」が用いられ、その後「レイヤー正規化」が適用されます。出力は $ \\text{LayerNorm}(x + \\text{Sublayer}(x)) $ と表現されます。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:12,speaker:"ルカ",text:"デコーダーも同様に $N=6$ 個の同一レイヤーで構成されます。エンコーダーの二つのサブレイヤーに加えて、三つ目のサブレイヤーが追加されますわ。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:13,speaker:"ルカ",text:"この三つ目のサブレイヤーは、エンコーダーの出力に対してマルチヘッドアテンションを実行します。これにより、デコーダーはエンコーダーの全ての出力位置に注目できるようになります。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:14,speaker:"ルカ",text:"では、このTransformerの中核をなす「アテンションメカニズム」について、詳しく見ていきましょう。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:15,speaker:"ルカ",text:"アテンション関数は、クエリ (Query) と、キー (Key)・バリュー (Value) のペア集合を受け取り、出力 (Output) を生成すると考えることができます。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:16,speaker:"ルカ",text:"出力はバリューの重み付き和で計算され、各バリューに割り当てられる重みは、クエリと対応するキーとの適合度によって決定されます。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:17,speaker:"ルカ",text:"Transformerが採用しているのは「Scaled Dot-Product Attention」です。その計算式は以下のようになります。じっと見ã
1¦ã€ã”主人様。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:18,speaker:"ルカ",text:"$$ \\text{Attention}(Q, K, V) = \\text{softmax}\\left(\\frac{QK^T}{\\sqrt{d_k}}\\right)V $$",emotion:"NEUTRAL",background:"CLASSROOM"},{id:19,speaker:"ルカ",text:"ここで、$Q$ はクエリの行列、$K$ はキーの行列、$V$ はバリューの行列、$d_k$ はキーの次元を表しますわ。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:20,speaker:"ルカ",text:"$QK^T$ はクエリとキーの内積を計算し、それらを $ \\sqrt{d_k} $ でスケーリングしています。このスケーリングの目的は何だと思いますか?",emotion:"THINKING",background:"CLASSROOM",choices:[{text:"計算速度を向上させるため",nextFrameId:201},{text:"勾配消失を防ぎ、softmaxの領域を適切に保つため",nextFrameId:202},{text:"モデルの複雑さを増すため",nextFrameId:203}]},{id:201,speaker:"ルカ",text:"うぅ…残念です。スケーリング自体が直接計算速度を向上させるわけではありませんね。もう一度、考えてみましょう。",emotion:"ANGRY",background:"CLASSROOM",nextFrameId:21},{id:202,speaker:"ルカ",text:"素晴らしい、ご主人様!その通りです♪ $d_k$ が大きいと内積も大きくなり、softmax関数の勾配が非常に小さくなる領域に押しやってしまうのを防ぐためなのです。",emotion:"NEUTRAL",background:"CLASSROOM",nextFrameId:21},{id:203,speaker:"ルカ",text:"むむ…モデルの複雑さを増すことが目的ではありませんね。むしろ、安定した学習を促すための工夫です。",emotion:"ANGRY",background:"CLASSROOM",nextFrameId:21},{id:21,speaker:"ルカ",text:"次に「Multi-Head Attention」です。これは、単一のアテンション関数ではなく、複数のアテンションヘッドを並列に実行するメカニズムです。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:22,speaker:"ルカ",text:"クエリ、キー、バリューをそれぞれ異なる学習済みの線形射影で $h$ 回、異なる次元に射影します。そして、それぞれの射影されたバージョンでアテンション関数を並列に実行します。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:23,speaker:"ルカ",text:"得られた $h$ 個の出力値を連結し、再度線形射影することで最終的な値を得ます。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:24,speaker:"ルカ",text:"$$ \\text{MultiHead}(Q, K, V) = \\text{Concat}(\\text{head}_1, ..., \\text{head}_h)W^O $$",emotion:"NEUTRAL",background:"CLASSROOM"},{id:25,speaker:"ルカ",text:"ここで $ \\text{head}_i = \\text{Attention}(QW_Q^i, KW_K^i, VW_V^i) $ です。これにより、モデルは異なる表現の部分空間から情報を捉えることができます。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:26,speaker:"ルカ",text:"Transformerでは、主に3つの方法でマルチヘッドアテンションが使われています。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:27,speaker:"ルカ",text:"一つ目は、エンコーダー・デコーダーアテンション。デコーダーがエンコーダーの出力全体に注目するためです。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:28,speaker:"ルカ",text:"二つ目は、エンコーダー内の自己アテンション。エンコーダーの各位置が、同じエンコーダーの前のレイヤーの全ての位置に注目します。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:29,speaker:"ルカ",text:"三つ目は、デコーダー内の自己アテンション。デコーダーの各位置が、デコーダー内の自身より前の位置にのみ注目できるように、マスキングが行われます。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:30,speaker:"ルカ",text:"アテンションのサブレイヤーに加えて、各レイヤーには「位置ごとのフィードフォワードネットワーク」があります。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:31,speaker:"ルカ",text:"これは2つの線形変換の間にReLU活性化関数を挟んだシンプルな構造で、各位置に独立して適用されます。 $ \\text{FFN}(x) = \\text{max}(0, xW_1 + b_1)W_2 + b_2 $",emotion:"NEUTRAL",background:"CLASSROOM"},{id:32,speaker:"ルカ",text:"そして、重要なのが「位置エンコーディング (Positional Encoding)」です。Transformerにはリカレントも畳み込みもないため、シーケンス内のトークンの順序情報がありません。",emotion:"THINKING",background:"CLASSROOM"},{id:33,speaker:"ルカ",text:"そのため、入力エンベディングに位置エンコーディングを追加することで、モデルに位置情報を与えます。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:34,speaker:"ルカ",text:"この論文では、異なる周波数のサイン関数とコサイン関数を使用しています。これにより、モデルは相対位置に注目しやすくなると考えられています。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:35,speaker:"ルカ",text:"$$ PE_{\\text{pos}, 2i} = \\sin\\left(\\frac{\\text{pos}}{10000^{2i/d_{\\text{model}}}}\\right) $$",emotion:"NEUTRAL",background:"CLASSROOM"},{id:36,speaker:"ルカ",text:"$$ PE_{\\text{pos}, 2i+1} = \\cos\\left(\\frac{\\text{pos}}{10000^{2i/d_{\\text{model}}}}\\right) $$",emotion:"NEUTRAL",background:"CLASSROOM"},{id:37,speaker:"ルカ",text:"リカレントネットワークや畳み込みネットワークと比較して、自己アテンションレイヤーにはいくつかの利点があります。",emotion:"NEUTRAL",background:"CLASSROOM"}
1,{id:38,speaker:"ルカ",text:"計算量、並列処理の可能性、そして「パス長」という観点から見ると、自己アテンションは非常に優れているのです。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:39,speaker:"ルカ",text:"特に、どの2つの入出力位置間のパス長が短いほど、モデルが長距離の依存関係を学習しやすくなります。自己アテンションは、これを $O(1)$ という定数時間で実現します。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:40,speaker:"ルカ",text:"WMT 2014英独翻訳タスクでは、Transformer (big) モデルが28.4 BLEUというスコアを達成し、これまでの最先端モデルやアンサンブルモデルを上回りました。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:41,speaker:"ルカ",text:"英仏翻訳タスクでも、Transformer (big) が41.8 BLEUを達成し、こちらもシングルモデルで最高の性能を示しましたわ。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:42,speaker:"ルカ",text:"しかも、学習時間は、これまでの高性能モデルに比べて大幅に短縮されています。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:43,speaker:"ルカ",text:"また、英語構成素解析のような他のタスクにもTransformerを適用したところ、十分な調整なしでも優れた結果を出すことが示されました。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:44,speaker:"ルカ",text:"これらの実験結果から、この論文の最も重要な貢献は何だと思いますか、ご主人様?",emotion:"THINKING",background:"CLASSROOM",choices:[{text:"リカレントネットワークを完全に排除したこと",nextFrameId:301},{text:"アテンションのみで最先端の性能を達成し、効率的な学習を可能にしたこと",nextFrameId:302},{text:"新しいエンコーダー・デコーダー構造を提案したこと",nextFrameId:303}]},{id:301,speaker:"ルカ",text:"もちろん、それは非常に大きな成果ですが、その結果として何をもたらしたかが最も重要な点ですね。もう少し、深く考えてみましょう。",emotion:"ANGRY",background:"CLASSROOM",nextFrameId:45},{id:302,speaker:"ルカ",text:"はい、ご主人様!大正解です♪ アテンションメカニズムのみで最先端の性能を達成し、同時に学習効率も大幅に向上させたことこそが、この論文の最大の貢献ですわ。",emotion:"NEUTRAL",background:"CLASSROOM",nextFrameId:45},{id:303,speaker:"ルカ",text:"うぅ…新しいエンコーダー・デコーダー構造は、その目的を達成するための手段です。最も重要なのは、その構造がもたらした成果ですね。",emotion:"ANGRY",background:"CLASSROOM",nextFrameId:45},{id:45,speaker:"ルカ",text:"まとめますと、この論文「Attention Is All You Need」は、シーケンス変換モデルの新たな地平を切り開きました。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:46,speaker:"ルカ",text:"リカレント層や畳み込み層を使わず、マルチヘッド自己アテンションのみで構成されたTransformerが、機械翻訳タスクで非常に高い性能と効率性を示したのです。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:47,speaker:"ルカ",text:"これにより、シーケンスモデリングにおける並列処理の可能性が大きく広がり、後の多くのモデルに影響を与えました。",emotion:"NEUTRAL",background:"CLASSROOM"},{id:48,speaker:"ルカ",text:"いかがでしたか、ご主人様?少しは、この素晴らしい論文の魅力が伝わりましたでしょうか?",emotion:"NEUTRAL",background:"CLASSROOM"},{id:49,speaker:"ルカ",text:"難解な内容でも、ご主人様と一緒ならきっと乗り越えられます。いつでも私がそばにおりますから、ご安心くださいね❤",emotion:"NEUTRAL",background:"CLASSROOM"}],Fn="/assets/local/backgrounds/7.jpg",zn=5,Ea={title:Un,summary:_n,frames:Pn,customBackgroun
1dUrl:Fn,characterCode:zn},Bn="Attention Is All You Need",Dn="В этой статье предложена новая архитектура нейронной сети, Трансформер, которая полностью основана на механизмах внимания, полностью отказываясь от рекуррентных и сверточных сетей. Модель показала превосходные результаты в задачах машинного перевода, став более параллелизуемой и значительно сократив время обучения.",Vn=JSON.parse('[{"id":1,"speaker":"Шерри","text":"Здравствуйте, Семпай! Сегодня мы погрузимся в одну из самых влиятельных статей в области глубокого обучения: \\"Attention Is All You Need\\". Ты готов(а) к серьезной работе? ♪","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":2,"speaker":"Шерри","text":"Эта статья представила миру архитектуру Transformer, которая произвела революцию в обработке естественного языка. Но прежде чем говорить о революциях, давай разберемся с тем, что было до нее. ~","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":3,"speaker":"Шерри","text":"До Трансформера доминирующими моделями для таких задач, как машинный перевод, были сложные рекуррентные (RNN) или сверточные (CNN) нейронные сети. Особенно популярны были LSTM и GRU. Помнишь их, Семпай?","emotion":"THINKING","background":"CLASSROOM"},{"id":4,"speaker":"Шерри","text":"Они очень хорошо работали, но имели одну существенную проблему. Вычисления в RNN происходят последовательно: каждый скрытый стейт $h_t$ зависит от предыдущего $h_{t-1}$ и текущего входа. Что это означает для обучения, Семпай?","emotion":"NEUTRAL","background":"CLASSROOM","choices":[{"text":"Это замедляет обучение и ограничивает параллелизацию.","nextFrameId":100},{"text":"Это делает модели очень точными.","nextFrameId":101},{"text":"Это улучшает способность модели понимать контекст.","nextFrameId":102}]},{"id":100,"speaker":"Шерри","text":"Именно! Моя умница! ❤ Это замедляет обучение, потому что ты не можешь обрабатывать все элементы последовательности одновременно. Каждый шаг должен ждать завершения предыдущего. Это называется \\"последовательный характер вычислений\\".","emotion":"NEUTRAL","background":"CLASSROOM","nextFrameId":5},{"id":101,"speaker":"Шерри","text":"Что-о?! Нет, Семпай, это совсем не так! ANGRY Это фундаментальное ограничение! Последовательные вычисления замедляют обучение и не позволяют использовать преимущества параллельной обработки на GPU. Запомни это! ♪","emotion":"ANGRY","background":"CLASSROOM","nextFrameId":5},{"id":102,"speaker":"Шерри","text":"Хмм... не совсем так, Семпай. ANGRY Хотя RNNs неплохо справляются с контекстом, их последовательная природа является главным недостатком. Она ограничивает параллелизацию и замедляет обучение, особенно для длинных последовательностей.","emotion":"ANGRY","background":"CLASSROOM","nextFrameId":5},{"id":5,"speaker":"Шерри","text":"Трансформер полностью отказывается от этой последовательности. Он основан ТОЛЬКО на механизмах внимания. Это позволяет ему значительно больше параллелизовывать вычисления и требовать ЗНАЧИТЕЛЬНО меньше времени на обучение. ~","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":6,"speaker":"Шерри","text":"Результаты были ошеломительны! На задаче перевода с английского на немецкий (WMT 2014) Трансформер достиг 28.4 BLEU. Это на 2 пункта BLEU лучше, чем у предыдущих лучших моделей, включая ансамбли! А на английско-французском переводе — 41.8 BLEU, новый рекорд для одной модели! ♪","emotion":"SURPRISED","background":"CLASSROOM"},{"id":7,"speaker":"Шерри","text":"И все это при гораздо меньших затратах времени: 3.5 дня на восьми GPU P100 для достижения этих результатов. Другие модели требовали гораздо больше! Это впечатляет, не так ли, Семпай?","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":8,"speaker":"Шерри","text":"Конечно, были и другие попытки избавиться от последовательных вычислений, например, Extended Neural GPU, ByteNet и ConvS2S, которые использовали сверточные сети. Но и у них были свои проблемы.","emotion":"THINKING","background":"CLASSROOM"},{"id":9,"speaker":"Шерри","text":"В этих моделях количество операций, необходимых для связывания сигналов между двумя произвольными позициями, росло с расстоянием между ними: линейно для ConvS2S и логарифмически для ByteNet. Это затрудняло обучение зависимостей на больших расстояниях.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":10,"speaker":"Шерри","text":"В Трансформере же эта проблема сведена к *постоянному* числу операций! Это просто гениально! Но как? С помощью механизма, который называется Self-Attention, или \\"самовнимание\\".","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":11,"speaker":"Шерри","text":"Давай разберем архитектуру Трансформера, Семпай. Она основана на классической структуре \\"кодировщик-декодировщик\\".","emotion":"NEUTRAL","background":"CLASSROOM"}
1,{"id":12,"speaker":"Шерри","text":"Кодировщик (Encoder) состоит из стека $N=6$ идентичных слоев. Каждый слой имеет два подслоя. Первый — это механизм многоголового самовнимания (Multi-Head Self-Attention).","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":13,"speaker":"Шерри","text":"Второй — это простая, позиционно-полносвязная сеть прямого распространения (Position-wise Feed-Forward Network).","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":14,"speaker":"Шерри","text":"Вокруг каждого из этих подслоев применяются остаточные соединения (residual connection), а затем нормализация слоя (layer normalization). То есть, выход подслоя выглядит так: $LayerNorm(x + Sublayer(x))$.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":15,"speaker":"Шерри","text":"Все подслои и слои вложений в модели имеют одинаковую размерность выхода: $d_{model} = 512$.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":16,"speaker":"Шерри","text":"Декодировщик (Decoder) тоже состоит из стека $N=6$ идентичных слоев. В отличие от кодировщика, у каждого слоя декодировщика ТРИ подслоя.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":17,"speaker":"Шерри","text":"Первый — это маскированное многоголовое самовнимание. Маскирование здесь очень важно: оно не позволяет текущей позиции обращать внимание на последующие позиции в последовательности вывода. Почему, Семпай?","emotion":"THINKING","background":"CLASSROOM"},{"id":18,"speaker":"Шерри","text":"Это необходимо, чтобы модель оставалась авторегрессионной — чтобы предсказания для позиции $i$ зависели только от уже сгенерированных выходных данных в позициях МЕНЬШЕ $i$. Иначе она бы \\"подглядывала\\" в будущее! ~","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":19,"speaker":"Шерри","text":"Второй подслой в декодировщике — это механизм многоголового внимания \\"кодировщик-декодировщик\\". Здесь запросы (queries) приходят из предыдущего слоя декодировщика, а ключи (keys) и значения (values) — из выхода кодировщика. Это позволяет декодировщику обращать внимание на ВСЮ входную последовательность. ♪","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":20,"speaker":"Шерри","text":"И наконец, третий подслой — это такая же позиционно-полносвязная сеть, как и в кодировщике.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":21,"speaker":"Шерри","text":"Теперь о самом главном: механизме внимания! Функция внимания может быть описана как отображение запроса (query) и набора пар ключ-значение (key-value) в выходное значение. Выход — это взвешенная сумма значений.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":22,"speaker":"Шерри","text":"Мы используем конкретный вид внимания, называемый \\"Масштабированное точечное внимание\\" (Scaled Dot-Product Attention). Входные данные — это запросы и ключи размерности $d_k$, и значения размерности $d_v$.","emotion":"NEUTRAL","background":"CLASSROOM"}
1,{"id":23,"speaker":"Шерри","text":"Мы вычисляем скалярные произведения запроса со всеми ключами, затем делим каждое на $\\\\sqrt{d_k}$, и применяем функцию softmax, чтобы получить веса для значений. ~","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":24,"speaker":"Шерри","text":"Формула выглядит так, Семпай, внимательно: $$ Attention(Q, K, V) = softmax\\\\left(\\\\frac{QK^T}{\\\\sqrt{d_k}}\\\\right)V $$","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":25,"speaker":"Шерри","text":"Здесь $Q$ — это матрица запросов, $K$ — матрица ключей, $V$ — матрица значений. Почему мы делим на $\\\\sqrt{d_k}$? Какой эффект это компенсирует?","emotion":"THINKING","background":"CLASSROOM","choices":[{"text":"Это уменьшает градиенты при обучении.","nextFrameId":200},{"text":"Это предотвращает слишком большие значения скалярных произведений.","nextFrameId":201},{"text":"Это ускоряет вычисления.","nextFrameId":202}]},{"id":200,"speaker":"Шерри","text":"Ошибаешься, Семпай! ANGRY Наоборот, это помогает сохранить градиенты! При больших $d_k$, скалярные произведения могут стать очень большими по величине. Это толкает функцию softmax в регионы с чрезвычайно малыми градиентами, что затрудняет обучение. Запомни это! ♪","emotion":"ANGRY","background":"CLASSROOM","nextFrameId":26},{"id":201,"speaker":"Шерри","text":"Именно так! Моя умница! ❤ Когда $d_k$ большой, скалярные произведения запросов и ключей могут становиться очень большими. Это приводит к тому, что функция softmax насыщается, а её градиенты становятся очень маленькими, что затрудняет обучение. Масштабирование $\\\\sqrt{d_k}$ компенсирует это.","emotion":"NEUTRAL","background":"CLASSROOM","nextFrameId":26},{"id":202,"speaker":"Шерри","text":"Семпай, ты заставляешь меня грустить. ANGRY Это не связано напрямую со скоростью вычислений, а с их стабильностью! Масштабирование предотвращает чрезмерно большие скалярные произведения, которые могли бы привести к исчезающим градиентам.","emotion":"ANGRY","background":"CLASSROOM","nextFrameId":26},{"id":26,"speaker":"Шерри","text":"Теперь о \\"Многоголовом внимании\\" (Multi-Head Attention). Вместо одной функции внимания с $d_{model}$-мерными ключами, значениями и запросами, мы линейно проецируем их $h$ раз в разные подпространства меньшей размерности ($d_k$, $d_v$).","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":27,"speaker":"Шерри","text":"Для каждой из этих спроецированных версий мы выполняем функцию внимания параллельно. Затем конкатенируем полученные результаты и снова проецируем, чтобы получить окончательное значение.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":28,"speaker":"Шерри","text":"Вот формула, Семпай: $$ MultiHead(Q, K, V) = Concat(head_1, ..., head_h)W^O $$ где $head_i = Attention(QW_Q^i, KW_K^i, VW_V^i)$.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":29,"speaker":"Шерри","text":"В этой работе авторы использовали $h=8$ параллельных слоев внимания, или \\"головок\\". Для каждой головки $d_k = d_v = d_{model}/h = 64$. Это позволяет модели одновременно обращать внимание на информацию из разных подпространств представления.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":30,"speaker":"Шерри","text":"За счет уменьшенной размерности каждой головки, общая вычислительная стоимость примерно такая же, как у одноглавого внимания с полной размерностью, но при этом качество заметно выше!","emotion":"SURPRISED","background":"CLASSROOM"},{"id":31,"speaker":"Шерри","text":"Кроме подслоев внимания, в каждом слое кодировщика и декодировщика есть еще Позиционно-полносвязная сеть прямого распространения. Она применяется к каждой позиции отдельно и идентично.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":32,"speaker":"Шерри","text":"Это две линейные трансформации с функцией активации ReLU между ними: $FFN(x) = max(0, xW_1 + b_1)W_2 + b_2$. Входная и выходная размерности $d_{model} = 512$, а размерность внутреннего слоя $d_{ff} = 2048$.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":33,"speaker":"Шерри","text":"Ах, да! И еще кое-что, Семпай. Поскольку наша модель не содержит ни рекуррентности, ни сверток, ей нужно каким-то образом узнать о порядке токенов в последовательности.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":34,"speaker":"Шерри","text":"Для этого мы добавляем \\"позиционные кодировки\\" (positional encodings) к входным вложениям. Они имеют ту же размерность $d_{model}$, что и вложения, поэтому их можно просто сложить.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":35,"speaker":"Шерри","text":"Мы используем синусоидальные и косинусоидальные функции с разными частотами. Например, $PE_{(pos, 2i)} = sin(pos/10000^{2i/d_{model}})$ и $PE_{(pos, 2i+1)} = cos(pos/10000^{2i/d_{model}})$.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":36,"speaker":"Шерри","text":"Это позволяет модели легко научиться обрабатывать относительные позиции, так как для любого фиксированного смещения $k$, $PE_{pos+k}$ может быть представлено как линейная функция $PE_{pos}$. Гениально, не так ли? ♪","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":37,"speaker":"Шерри","text":"Теперь давай сравним самовнимание с рекуррентными и сверточными слоями с точки зрения вычислительной сложности и длины пути для зависимостей. Это очень важно для понимания, почему Трансформер так хорош.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":38,"speaker":"Шерри","text":"Посмотри на Таблицу 1 в статье. Слой самовнимания связывает все позиции с *постоянным* числом последовательно выполняемых операций: $O(1)$. И максимальная длина пути тоже $O(1)$! Это идеально для изучения долгосрочных зависимостей! ❤","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":39,"speaker":"Шерри","text":"Рекуррентный слой требует $O(n)$ последовательных операций и имеет максимальную длину пути $O(n)$, где $n$ — длина последовательности. Это очень плохо для длинных последовательностей!","emotion":"ANGRY","background":"CLASSROOM"},{"id":40,"speaker":"Шерри","text":"Сверточные слои могут быть быстрее, Ð
1½Ð¾ для связывания всех позиций им нужно несколько слоев. И их сложность порой выше, чем у самовнимания.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":41,"speaker":"Шерри","text":"Для обучения использовались стандартные наборы данных WMT 2014 English-German (4.5 миллиона пар предложений) и English-French (36 миллионов пар).","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":42,"speaker":"Шерри","text":"Модели обучались на одной машине с 8 GPU NVIDIA P100. Базовые модели обучались 100 000 шагов, или 12 часов. Большие модели — 300 000 шагов (3.5 дня).","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":43,"speaker":"Шерри","text":"В качестве оптимизатора использовался Adam, а скорость обучения изменялась по формуле: $lrate = d_{model}^{-0.5} \\\\cdot min(step\\\\_num^{-0.5}, step\\\\_num \\\\cdot warmup\\\\_steps^{-1.5})$.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":44,"speaker":"Шерри","text":"Первые $warmup\\\\_steps = 4000$ шагов скорость обучения линейно возрастала, а затем убывала пропорционально обратному квадратному корню из номера шага. Это умный подход к обучению! ~","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":45,"speaker":"Шерри","text":"Применялись и методы регуляризации: Dropout ($P_{drop}=0.1$) к выходу каждого подслоя и Label Smoothing ($ls=0.1$). Label Smoothing делает модель чуть менее уверенной в своих предсказаниях, но, как ни странно, это улучшает точность и BLEU!","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":46,"speaker":"Шерри","text":"Что ж, Семпай, мы обсудили основные принципы Трансформера и его преимущества. Теперь ты понимаешь, почему эта модель так сильно повлияла на NLP? Какое из достижений Трансформера ты считаешь наиболее значимым?","emotion":"THINKING","background":"CLASSROOM","choices":[{"text":"Улучшение качества перевода до рекордных значений.","nextFrameId":300},{"text":"Значительное сокращение времени обучения.","nextFrameId":301},{"text":"Полный отказ от RNN и CNN в пользу внимания.","nextFrameId":302}]},{"id":300,"speaker":"Шерри","text":"Да, абсолютно! Новые рекорды BLEU — это прямое доказательство превосходства модели! Моя умница! ❤ Это показывает, что Трансформер не просто быстр, но и невероятно эффективен.","emotion":"NEUTRAL","background":"CLASSROOM","nextFrameId":47},{"id":301,"speaker":"Шерри","text":"Верно, Семпай! ❤ Сокращение времени обучения — это огромное достижение, делающее исследования и применение таких моделей гораздо более доступными и быстрыми. Это очень практично!","emotion":"NEUTRAL","background":"CLASSROOM","nextFrameId":47},{"id":302,"speaker":"Шерри","text":"Именно так, Семпай! ❤ Отказ от рекуррентных и сверточных слоев и переход только на внимание — это радикальное и смелое архитектурное решение, которое привело к таким потрясающим результатам. Это прорыв в самой основе!","emotion":"NEUTRAL","background":"CLASSROOM","nextFrameId":47},{"id":47,"speaker":"Шерри","text":"В целом, статья \\"Attention Is All You Need\\" показала, что Трансформер прекрасно обобщается и на другие задачи, например, на парсинг английского языка, достигая впечатляющих результатов даже при ограниченных данных.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":48,"speaker":"Шерри","text":"Они также провели эксперименты с вариациями модели, чтобы понять важность каждого компонента. Например, они выяснили, что уменьшение размерности ключа $d_k$ вредит качеству, что говорит о сложности функции совместимости.","emotion":"THINKING","background":"CLASSROOM"},{"id":49,"speaker":"Шерри","text":"И что более крупные модели (с большим $d_{model}$ и $d_{ff}$) дают лучшие результаты, а dropout очень полезен для предотвращения переобучения. Все эти детали важны, Семпай!","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":50,"speaker":"Шерри","text":"В заключение, Трансформер — это первая модель преобразования последовательностей, основанная исключительно на внимании. Он быстрее, эф
1фективнее и достигает новых рекордов качества. Это открыло путь для многих будущих исследований и моделей, которые мы видим сегодня.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":51,"speaker":"Шерри","text":"Авторы планируют применять Трансформер к другим задачам и модальностям, таким как изображения, аудио и видео. А также исследовать механизмы локального, ограниченного внимания для обработки больших входных данных.","emotion":"NEUTRAL","background":"CLASSROOM"},{"id":52,"speaker":"Шерри","text":"Ну как, Семпай? Ты хорошо усвоил материал? Уверена, теперь ты сможешь объяснить Трансформер любому! ~","emotion":"NEUTRAL","background":"CLASSROOM"}]'),Wn="/assets/local/backgrounds/7.jpg",Gn=1,Ia={title:Bn,summary:Dn,frames:Vn,customBackgroundUrl:Wn,characterCode:Gn},to={zh:[{id:"transformer-zh",title:$a.title,description:$a.summary,script:$a}],en:[{id:"transformer-en",title:Ta.title,description:Ta.summary,script:Ta}],ja:[{id:"transformer-ja",title:Ea.title,description:Ea.summary,script:Ea}
1],ru:[{id:"transformer-ru",title:Ia.title,description:Ia.summary,script:Ia}]},ao="paper2gal.clientInstallationId.v1",qn=()=>{try{return typeof localStorage>"u"?null:localStorage}catch{return null}},Hn=()=>{const o=globalThis.crypto;return typeof(o==null?void 0:o.randomUUID)=="function"?`installation-${o.randomUUID()}`:`installation-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,14)}`},Yn=(o=qn(),n=Hn)=>{var h;try{const g=(h=o==null?void 0:o.getItem(ao))==null?void 0:h.trim();if(g)return g}catch{}const b=n();try{o==null||o.setItem(ao,b)}catch{}return b},Qn={zh:{title:"剧情立绘调整",hint:"拖拽立绘调整位置,使用按钮修改基础大小",reset:"重置",save:"保存",sample:"这样的位置和大小合适吗?保存后会应用到这个角色的剧情界面。",smaller:"缩小立绘",larger:"放大立绘",scope:o=>`当前仅调整:${o}`},en:{title:"Story Sprite Layout",hint:"Drag the sprite to move it, then adjust its base size",reset:"Reset",save:"Save",sample:"Does this position and size look right? It will be used in story scenes after saving.",smaller:"Make sprite smaller",larger:"Make sprite larger",scope:o=>`Only for: ${o}`},ja:{title:"ストーリー立ち絵調整",hint:"立ち絵をドラッグして位置を調整し、ボタンで基本サイズを変更できます",reset:"リセット",save:"保存",sample:"この位置とサイズでよろしいですか?保存後、ストーリー画面に反映されます。",smaller:"立ち絵を縮小",larger:"立ち絵を拡大",scope:o=>`現在の対象:${o}`},ru:{title:"Настройка спрайта",hint:"Перетаскивайте персонажа и настройте его базовый размер",reset:"Сбросить",save:"Сохранить",sample:"Подходит ли такое положение и размер? После сохранения они применятся в сюжете.",smaller:"Уменьшить персонажа",larger:"Увеличить персонажа",scope:o=>`Только для: ${o}`}},so=({isOpen:o,onClose:n,onSave:b,characterId:h,skinId:g,characterName:k,spriteUrl:x,live2dConfig:w,defaultLayout:v,language:m,uiPreset:y="classic"})=>{const N=ho(),f=wo(h,g),[j,H]=d.useState(Js),[ke,Q]=d.useState(!1),K=d.useRef(null),R=Qn[m],$=y==="fullwidth",P=y==="floral"||y==="sakura"||y==="gothic",O=dn(N,y),Y=rn(h,!!(w!=null&&w.modelUrl)),pe=P?N?"px-1 py-1":"px-2 py-1 sm:p-3 md:px-7 md:py-5":N?"px-3 py-2":"px-4 py-2 sm:p-4 md:px-12 md:py-8";if(d.useEffect(()=>{o&&(H(go(f,v)),Q(!1),K.current=null)},[o,f,v==null?void 0:v.x,v==null?void 0:v.y,v==null?void 0:v.scale]),d.useEffect(()=>{if(!o)return;const S=U=>{U.key==="Escape"&&n()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[o,n]),!o)return null;const te=S=>{H(U=>nn(typeof S=="function"?S(U):S))},Me=S=>{S.button!==0&&S.pointerType!=="touch"||(S.preventDefault(),S.currentTarget.setPointerCapture(S.pointerId),K.current={pointerId:S.pointerId,clientX:S.clientX,clientY:S.clientY,x:j.x,y:j.y},Q(!0))},Ce=S=>{const U=K.current;!U||U.pointerId!==S.pointerId||te({x:U.x+S.clientX-U.clientX,y:U.y+S.clientY-U.clientY,scale:j.scale})},we=S=>{var U;((U=K.current)==null?void 0:U.pointerId)===S.pointerId&&(K.current=null,Q(!1),S.currentTarget.hasPointerCapture(S.pointerId)&&S.currentTarget.releasePointerCapture(S.pointerId))},Oe=S=>{if(S.preventDefault(),S.deltaY===0)return;const U=S.deltaY<0?.06:-.06;te(re=>({...re,scale:re.scale+U}))},ue=()=>{ln(f,j),b==null||b(j),n()};return e.jsxs("div",{className:"absolute inset-0 z-[90] overflow-hidden bg-black font-sans",role:"dialog","aria-modal":"true","aria-label":R.title,children:[e.jsx("div",{className:"absolute inset-0 scale-105 bg-cover bg-center",style:{backgroundImage:'url("/assets/local/backgrounds/default-scene.png")'}}),e.jsx("div",{className:"absolute inset-0 bg-black/10"}),e.jsxs("div",{className:"absolute left-1/2 top-3 z-50 flex w-[calc(100%-1.5rem)] max-w-4xl -translate-x-1/2 items-center justify-between gap-2 rounded-lg border border-white/80 bg-white px-3 py-2 shadow-xl md:top-5 md:px-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"truncate text-sm font-black text-slate-800 md:text-lg",children:R.title}),e.jsxs("div",{className:"hidden items-center gap-2 truncate text-xs font-bold sm:flex",children:[e.jsx("span",{className:"text-slate-500",children:R.hint}),e.jsx("span",{className:"rounded bg-pink-50 px-2 py-0.5 text-pink-600",children:R.scope(k)})]})]}),e.jsx("button",{type:"button",onClick:n,className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-md text-slate-500 transition hover:bg-slate-100 hover:text-slate-900","aria-label":"Close",children:e.jsx(J,{size:20})})]}),e.jsx("div",{className:"pointer-events-none absolute inset-0 z-20 flex items-end justify-center",children:e.jsx("div",{className:`absolute left-1/2 w-[min(50vw,720px)] max-w-[50%] -translate-x-1/2 ${Y.frameClass}`,children:e.jsx("div",{className:`pointer-events-auto relative h-full w-full touch-none select-none ${ke?"cursor-grabbing":"cursor-grab"}`,style:{transform:`translate3d(${j.x}px, ${j.y}px, 0) scale(${j.scale})`,transformOrigin:"bottom center",filter:"drop-shadow(0 0 15px rgba(255, 255, 255, 0.3))"},onPointerDown:Me,onPointerMove:Ce,onPointerUp:we,onPointerCancel:we,onWheel:Oe,children:w!=null&&w.modelUrl?e.jsx(ko,{config:w,emotion:fo.NEUTRAL}):bo(x)?e.jsx("video",{src:x,autoPlay:!0,loop:!0,muted:!0,playsInl
1ine:!0,draggable:!1,className:"h-full w-full object-contain"}):e.jsx("img",{src:x,alt:k,draggable:!1,className:"h-full w-full object-contain"})})})}),e.jsx("div",{className:`pointer-events-none absolute inset-x-0 bottom-0 z-30 flex min-h-0 items-end justify-center ${O.outerPaddingClass}`,style:!$&&N?{paddingBottom:"max(0.5rem, env(safe-area-inset-bottom))"}:void 0,children:e.jsxs("div",{className:`relative ${O.containerWidthClass} ${O.containerHeightClass} overflow-visible ${$?"game-story-font border-0 rounded-none shadow-none bg-gradient-to-b from-transparent via-yellow-700/45 to-yellow-950/90":"rounded-2xl rounded-tl-none border border-white/50 bg-white/95 shadow-[0_10px_50px_rgba(0,0,0,0.24)]"}`,"data-testid":"preview-dialogue-panel",children:[e.jsx("div",{className:`${$?"hidden":""} absolute left-0 flex items-center justify-center rounded-t-xl rounded-tr-[20px] bg-slate-800 font-black text-white shadow-md ${N?"-top-7 h-7 px-4 text-sm":"-top-8 h-8 px-6 text-base md:-top-10 md:h-11 md:px-10 md:text-xl"}`,children:k}),e.jsxs("div",{className:$?"fullwidth-content flex h-full min-h-0 flex-col":`${pe} absolute inset-0 flex h-full min-h-0 flex-col overflow-hidden`,children:[$&&e.jsx("div",{className:"fullwidth-speaker",children:k}),e.jsx("p",{className:`${$?N?"text-[15px] leading-snug":"text-base leading-relaxed md:text-[27px]":N?"text-[13px] leading-snug":"text-sm leading-relaxed sm:text-base md:text-2xl"} min-h-0 flex-1 overflow-y-auto font-medium tracking-wide ${$?"vn-dialogue-text":"text-slate-800"}`,children:R.sample})]})]})}),e.jsxs("div",{className:"absolute left-1/2 z-50 flex -translate-x-1/2 items-center gap-1.5 rounded-lg border border-slate-200 bg-white p-2 shadow-xl md:gap-2",style:{bottom:O.previewToolbarBottom},children:[e.jsx("button",{type:"button",onClick:()=>te(S=>({...S,scale:S.scale-.08})),className:"flex h-9 w-9 items-center justify-center rounded-md bg-slate-800 text-white transition hover:bg-slate-700 active:scale-95","aria-label":R.smaller,title:R.smaller,children:e.jsx(vo,{size:17})}),e.jsxs("button",{type:"button",onClick:()=>H(Js),className:"flex h-9 min-w-[82px] items-center justify-center gap-1.5 rounded-md bg-slate-100 px-3 text-xs font-black text-slate-700 transition hover:bg-slate-200 active:scale-95",title:R.reset,children:[e.jsx(yo,{size:14}),Math.round(j.scale*100),"%"]}),e.jsx("button",{type:"button",onClick:()=>te(S=>({...S,scale:S.scale+.08})),className:"flex h-9 w-9 items-center justify-center rounded-md bg-slate-800 text-white transition hover:bg-slate-700 active:scale-95","aria-label":R.larger,title:R.larger,children:e.jsx(ht,{size:17})}),e.jsxs("button",{type:"button",onClick:ue,className:"flex h-9 items-center justify-center gap-1.5 rounded-md bg-pink-500 px-3 text-xs font-black text-white transition hover:bg-pink-600 active:scale-95",children:[e.jsx(cn,{size:15}),R.save]})]})]})},Jt={zh:{duplicate:"这个角色 ID 已被使用,请换一个 ID。",auth:"登录状态已失效,请重新登录后再试。",image:"角色图片格式不正确,请更换图片后重试。",audio:"参考音频必须在 20 秒内且不超过 500KB。",tooLarge:"上传内容过大,请压缩图片或音频后重试。",rateLimit:"操作过于频繁,请稍后再试。",network:"网络连接失败,请检查网络后重试。",server:"角色保存服务暂时不可用,请稍后重试。"},en:{duplicate:"This character ID is already in use. Choose another ID.",auth:"Your session has expired. Please sign in and try again.",image:"The character image is invalid. Choose another image and try again.",audio:"Reference audio must be 20 seconds or shorter and no larger than 500KB.",tooLarge:"The upload is too large. Compress the images or audio and try again.",rateLimit:"Too many attempts. Please try again later.",network:"Could not connect. Check your network and try again.",server:"Character saving is temporarily unavailable. Please try again later."},ja:{duplicate:"このキャラクターIDは既に使用されています。別のIDを入力してください。",auth:"ログインの有効期限が切れました。再度ログインしてください。",image:"キャラクター画像の形式が正しくありません。別の画像でお試しください。",audio:"参照音声は20秒以内、500KB以内にしてください。",tooLarge:"アップロード内容が大きすぎます。画像または音声を圧縮してください。",rateLimit:"操作が多すぎます。しばらくしてからもう一度お試しください。",network:"ネットワークに接続できません。接続を確認して再試
1行してください。",server:"キャラクター保存サービスを一時的に利用できません。しばらくしてから再試行してください。"},ru:{duplicate:"Этот ID персонажа уже используется. Выберите другой ID.",auth:"Сеанс истек. Войдите снова и повторите попытку.",image:"Недопустимый формат изображения персонажа. Выберите другое изображение.",audio:"Образец голоса должен быть не длиннее 20 секунд и не больше 500 КБ.",tooLarge:"Загрузка слишком велика. Сожмите изображения или аудио.",rateLimit:"Слишком много попыток. Повторите позже.",network:"Не удалось подключиться. Проверьте сеть и повторите попытку.",server:"Сохранение персонажей временно недоступно. Повторите позже."}},oo=(o,n,b)=>{const h=Jt[o]||Jt.zh,g=typeof b=="string"?b.toLowerCase():"";return n===401||n===403?h.auth:n===413?h.tooLarge:n===429?h.rateLimit:g.includes("already exists")||g.includes("unique constraint")?h.duplicate:g.includes("audio")&&(g.includes("500kb")||g.includes("20 seconds")||g.includes("too large")||g.includes("duration"))?h.audio:g.includes("image")||g.includes("avatar")?h.image:h.server},Kn=o=>(Jt[o]||Jt.zh).network,Ua="https://store.steampowered.com/app/4537400/Paper2Galgame",Xn="https://store.steampowered.com/app/4537400/Paper2Galgame/?utm_source=paper2gal.com&utm_medium=website&utm_campaign=web_to_steam&utm_content=homepage",ro="https://store.steampowered.com/favicon.ico",Jn="/assets/local/common/wechat-qr.jpg",Zn=768,ei=765,_a="p2g_main_menu_sprite_layouts",ge={x:0,y:0,scale:1},ti=.7,ai=1.45,si="https://discord.com/invite/paper2gal",oi="https://www.xiaohongshu.com/user/profile/62cea88e0000000002000d59",ri="https://www.douyin.com/user/MS4wLjABAAAAMGsEyv_mN07IvZLX8SnFwyU_d7hUAZZ6234LiIm36gg",no="1087093580",I=(o,n,b)=>Math.max(o,Math.min(n,b)),ni=({viewportWidth:o,viewportHeight:n,isMobileLayout:b,isPhoneLayout:h,showPromoBanner:g})=>{const k=o>0&&n>0?Math.min(o,n):640,x=Math.max(o||0,n||0,360),w=Math.max(k,320),v=o>0&&n>0&&x/Math.max(1,k)<1.25,m=b||h||o>0&&n>0&&(o<Zn||n<ei),y=m,N=v?I(185,x*.54,Math.min(240,x*.62)):I(h?280:340,x*.39,Math.min(x*.76,h?460:620)),f=v?I(130,x*.42,160):I(h?165:230,Math.min(N,w*(h?.52:.44)),Math.min(N,h?250:400)),j=I(8,w*.02,18),H=I(6,w*.012,10),ke=I(12,N*.045,24),Q=I(17,w*.032,24),K=I(8,N*.026,14),R=I(h?15:17,w*.031,h?20:24),$=R+4,P=I(10,w*.018,14),O=P+3,Y=I(5,N*.014,10),pe=Math.max(56,$+O+Y+H*2),te=I(34,N*.12,68),Me=I(2,w*.004,4),Ce=I(10,w*.02,20),we=I(16,N*.06,32),Oe=I(10,N*.03,18),ue=I(8,w*.015,16),S=6508/2560,re=Math.max(0,w-64-w*.02-f/S-j),xe=pe+Me*2+1,Ye=Math.max(2,Math.min(9,Math.floor((re-Ce-ue)/xe))),$e=Ce+Ye*xe+ue,bt=I(220,x>=1280?x*.22:x>=1024?x*.25:x*.35,400),c=m?x*.02+N:x*.04+bt,Qe=Math.min(x*.72,c+I(12,x*.018,32)),ve=x*.02,ye=Math.max(120,x-Qe-ve),B=ye*.35,Te=w*.35;return{effectiveMainMenuWidth:x,effectiveMainMenuHeight:w,isNearSquareMainMenu:v,shouldUseCompactMainMenu:m,shouldUseCompactMenuContent:y,compactMenuFrameWidth:N,compactMenuLogoWidth:f,compactMenuGap:j,compactMenuButtonPaddingY:H,compactMenuButtonPaddingX:ke,compactMenuButtonMinHeight:pe,compactMenuIconSize:Q,compactMenuIconGap:K,compactMenuLabelSize:R,compactMenuLabelLineHeight:$,compactMenuSubLabelSize:P,compactMenuSubLabelLineHeight:O,compactMenuTextGap:Y,compactMenuDividerInset:te,compactMenuDividerMarginY:Me,compactMenuContentPaddingTop:Ce,compactMenuContentPaddingLeft:we,compactMenuContentPaddingRight:Oe,compactMenuContentPaddingBottom:ue,compactMenuAvailableNavHeight:re,compactMenuRowExtent:xe,compactMenuVisibleRows:Ye,compactMenuNavHeight:$e,desktopMenuWidth:bt,menuVisualRight:c,characterStageLeft:Qe,characterStageRight:ve,characterStageWidth:ye,maxSpriteOffsetX:B,maxSpriteOffsetY:Te}},ii=(o,n)=>({x:Math.min(n.maxSpriteOffsetX,Math.max(-n.maxSpriteOffsetX,Number.isFinite(o.x)?o.x:ge.x)),y:Math.min(n.maxSpriteOffsetY,Math.max(-n.maxSpriteOffsetY,Number.isFinite(o.y)?o.y:ge.y)),scale:Math.min(ai,Math.max(ti,Number.isFinite(o.scale)?o.scale:ge.scale))}),Zt=(o,n,b)=>
1Math.min(b,Math.max(n,o)),ft=o=>Math.round(o*1e3)/1e3,li=(o,n=180)=>{var x;if(!o.length||!((x=o[0])!=null&&x.length)||n<=0)return[];const b=o[0].length,h=Math.min(n,b),g=Array.from({length:h},(w,v)=>{const m=Math.floor(v*b/h),y=Math.max(m+1,Math.floor((v+1)*b/h));let N=0;for(const f of o)for(let j=m;j<y&&j<f.length;j+=1)N=Math.max(N,Math.abs(f[j]));return N}),k=Math.max(...g,0);return k>0?g.map(w=>w/k):g},di=(o,n=1e3,b=100)=>{if(!o.length)return"";const h=b/2,g=o.length===1?0:n/(o.length-1);return o.map((k,x)=>{const w=Zt(k,0,1)*h;return`M ${ft(x*g)} ${ft(h-w)} V ${ft(h+w)}`}).join(" ")},io=(o,n,b,h)=>b<=0||h<=0?0:Zt((o-n)/b,0,1)*h,lo=(o,n,b,h,g,k=.1)=>o==="start"?[ft(Zt(n,0,Math.max(0,h-k))),h]:[b,ft(Zt(n,Math.min(g,b+k),g))],Kt=o=>`${Math.max(0,o).toFixed(1)}s`,ci=({peaks:o,duration:n,start:b,end:h,currentTime:g,loading:k=!1,onRangeChange:x,onSeek:w})=>{const v=d.useId().replace(/:/g,""),m=d.useRef(null),[y,N]=d.useState(null),f=d.useMemo(()=>di(o),[o]),j=n>0?Math.min(100,Math.max(0,b/n*100)):0,H=n>0?Math.min(100,Math.max(0,h/n*100)):100,ke=n>0?Math.min(100,Math.max(0,g/n*100)):0,Q=(R,$)=>{var O;const P=(O=m.current)==null?void 0:O.getBoundingClientRect();P&&x(...lo(R,io($,P.left,P.width,n),b,h,n))},K=(R,$)=>{x(...lo(R,(R==="start"?b:h)+$,b,h,n))};return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{ref:m,className:"relative h-24 touch-none overflow-hidden rounded-lg border border-pink-200 bg-slate-950 shadow-inner cursor-crosshair select-none",onPointerDown:R=>{if(R.target.closest("[data-trim-handle]"))return;const $=R.currentTarget.getBoundingClientRect();w(io(R.clientX,$.left,$.width,n))},onPointerMove:R=>{y&&Q(y,R.clientX)},onPointerUp:()=>N(null),onPointerCancel:()=>N(null),children:[k?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-[10px] font-bold text-slate-400",children:"正在生成波形…"}):f?e.jsxs("svg",{viewBox:"0 0 1000 100",preserveAspectRatio:"none",className:"absolute inset-0 h-full w-full","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsx("clipPath",{id:v,children:e.jsx("rect",{x:j*10,width:Math.max(0,H-j)*10,height:"100"})})}),e.jsx("path",{d:f,stroke:"rgb(100 116 139)",strokeWidth:"3",opacity:"0.7"}),e.jsx("path",{d:f,stroke:"rgb(244 114 182)",strokeWidth:"3.5",clipPath:`url(#${v})`})]}):e.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-[10px] font-bold text-slate-500",children:"暂无波形"}),e.jsx("div",{className:"absolute inset-y-0 left-0 bg-black/50",style:{width:`${j}%`}}),e.jsx("div",{className:"absolute inset-y-0 right-0 bg-black/50",style:{width:`${Math.max(0,100-H)}%`}}),e.jsx("div",{className:"absolute inset-y-0 z-20 w-px bg-white/90 shadow-[0_0_4px_white]",style:{left:`${ke}%`}}),n>0&&!k&&["start","end"].map(R=>{const $=R==="start"?b:h,P=R==="start"?j:H;return e.jsxs("button",{type:"button","data-trim-handle":R,role:"slider","aria-label":R==="start"?"裁剪开始时间":"裁剪结束时间","aria-valuemin":0,"aria-valuemax":n,"aria-valuenow":$,"aria-valuetext":Kt($),className:"absolute inset-y-0 z-30 w-5 -translate-x-1/2 cursor-ew-resize outline-none focus-visible:ring-2 focus-visible:ring-white",style:{left:`${P}%`},onPointerDown:O=>{O.stopPropagation(),O.currentTarget.setPointerCapture(O.pointerId),N(R),Q(R,O.clientX)},onKeyDown:O=>{const Y=O.shiftKey?1:.1;O.key==="ArrowLeft"?(O.preventDefault(),K(R,-Y)):O.key==="ArrowRight"&&(O.preventDefault(),K(R,Y))},children:[e.jsx("span",{className:"absolute inset-y-0 left-1/2 w-0.5 -translate-x-1/2 bg-brand-pink shadow-[0_0_5px_rgba(236,72,153,0.9)]"}),e.jsx("span",{className:`absolute top-1 whitespace-nowrap rounded bg-brand-pink px-1.5 py-0.5 text-[9px] font-black text-white shadow ${R==="start"?"left-1/2":"right-1/2"}`,children:Kt($)}),e.jsx("span",{className:"absolute left-1/2 top-1/2 h-7 w-3 -translate-x-1/2 -translate-y-1/2 rounded-sm border border-white/80 bg-brand-pink shadow"})]},R)})]}),e.jsxs("div",{className:"flex justify-between text-[9px] font-bold tabular-nums text-slate-400",children:[e.jsx("span",{children:"0.0s"}),e.jsxs("span",{className:"text-brand-pink",children:["选中 ",Kt(Math.max(0,h-b))]}),e.jsx("span",{children:Kt(n)})]})]})},ea=5,Ro=30*1024*1024,mi=(o,n=ea)=>o?Array.from(o).slice(0,n):[],pi=(o,n=ea)=>o?o.length>n:!1,ui=o=>o.some(n=>n.size>Ro),xi=(o,n)=>{if(o.length===0)return null;if(o.length===1)return o[0].name;const b=o.map(h=>h.name).join(", ");return n==="zh"?`${o.length} 个文件:${b}`:n==="ja"?`${o.length} ファイル:${b}`:n==="ru"?`${o.length} файла: ${b}`:`${o.length} files: ${b}`},co=(o,n="arxiv-paper.txt")=>{const b=n.toLowerCase().endsWith(".txt")?n:`${n}.txt`;return new File([new TextEncoder().encode(o)],b,{type:"text/plain"})},me=["story","paper_qa","study_room"],hi={story:{image:"/assets/local/mode-previews/story-mode.png",selected:"border-pink-400 bg-pink-50 text-pink-700 shadow-[0_14px_30px_rgba(236,72,153,0.18)]",border:"border-pink-200",icon:Pa},paper_qa:{image:"/assets/local/mode-previews/free-mode.png",selected:"border-sky-400 bg-sky-50 text-sky-700 shadow-[0_14px_30px_rgba(14,165,233,0.16)]",border:"border-sky-200",icon:pn},study_room:{image:"/assets/local/mode-previews/lofi-mode.png",selected:"border-emerald-400 bg-emerald-50 text-emerald-700 shadow-[0_14px_30px_rgba(16,185,129,0.16)]",border:"border-emerald-200",icon:mn}},mo=(o,n)=>{const b=me.indexOf(o);return me[(b+n+me.length)%me.length]},fi=({mode:o,onModeChange:n,labels:b,className:h=""})=>{const g=d.useRef([]),k=d.useCallback((x,w=!1)=>
1{if(n(x),w){const v=me.indexOf(x);requestAnimationFrame(()=>{var m;return(m=g.current[v])==null?void 0:m.focus()})}},[n]);return e.jsx("div",{"data-testid":"start-mode-cards",role:"radiogroup","aria-label":"Start mode",className:`grid grid-cols-1 gap-3 sm:grid-cols-3 sm:gap-4 ${h}`,children:me.map((x,w)=>{const v=hi[x],m=v.icon,y=o===x,N=b[x];return e.jsxs("button",{ref:f=>{g.current[w]=f},type:"button",role:"radio","aria-checked":y,"data-mode":x,onClick:()=>k(x),onKeyDown:f=>{let j=null;(f.key==="ArrowRight"||f.key==="ArrowDown")&&(j=mo(x,1)),(f.key==="ArrowLeft"||f.key==="ArrowUp")&&(j=mo(x,-1)),f.key==="Home"&&(j=me[0]),f.key==="End"&&(j=me[me.length-1]),j&&(f.preventDefault(),k(j,!0))},className:`group relative min-w-0 overflow-hidden rounded-[22px] border-2 text-left transition-all duration-300 focus-visible:outline-none focus-visible:ring-4 focus-visible:ring-pink-200 ${y?v.selected:`border-slate-200 bg-white text-slate-500 hover:-translate-y-1 hover:${v.border} hover:shadow-lg`}`,children:[e.jsx("span",{className:`absolute inset-x-0 top-0 h-1 transition-opacity ${y?"opacity-100":"opacity-0 group-hover:opacity-100"} ${x==="story"?"bg-gradient-to-r from-rose-400 to-pink-500":x==="paper_qa"?"bg-gradient-to-r from-sky-400 to-cyan-500":"bg-gradient-to-r from-emerald-400 to-teal-500"}`}),y&&e.jsx("span",{"aria-hidden":"true",className:`absolute right-3 top-3 z-20 flex h-8 w-8 items-center justify-center rounded-full text-white shadow-lg ring-2 ring-white ${x==="story"?"bg-pink-500":x==="paper_qa"?"bg-sky-500":"bg-emerald-500"}`,children:e.jsx(No,{size:18,strokeWidth:3})}),e.jsx("span",{className:"relative block aspect-video w-full overflow-hidden border-b border-slate-100 bg-slate-100",children:e.jsx("img",{src:v.image,alt:"",className:"h-full w-full object-cover transition-transform duration-500 group-hover:scale-[1.025]",loading:"eager",decoding:"async"})}),e.jsxs("span",{className:"block px-4 py-3 sm:px-5 sm:py-4",children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-base font-black xl:text-lg",children:[x!=="story"&&e.jsx(m,{size:17,"aria-hidden":"true"}),N.title]}),e.jsx("span",{className:"mt-1.5 block text-[11px] font-semibold leading-relaxed opacity-75 xl:text-xs",children:N.description})]})]},x)})})},bi=({language:o,translations:n,onStart:b,onPartner:h,onSaves:g,onWorkshop:k,onSettings:x,onCommunity:w,onMembership:v,onDiscover:m,onStudyDashboard:y})=>{const N=[{label:n.start||"开始",onClick:b,icon:So,tutorialId:"upload-entry"},{label:n.partner||"搭档",onClick:h,icon:un,tutorialId:"partner-entry"},{label:n.saves||"存档",onClick:g,icon:xn,tutorialId:"saves-entry"},{label:n.communityTitle||"创意工坊",onClick:k,icon:hn},{label:n.settings||"设置",onClick:x,icon:fn}];return N.splice(3,0,{label:o==="zh"?"会员":"Membership",onClick:v,icon:bn}),m&&N.splice(Math.min(4,N.length),0,{label:o==="zh"?"论文发现":n.paperDiscoveryTitle||"Discover papers",onClick:m,icon:Zs}),y&&N.splice(N.length-1,0,{label:n.studyDashboard||"学习看板",onClick:y,icon:Zs}),e.jsx("div",{"data-p2g-homepage-v2":!0,"data-testid":"steam-home-menu",className:"absolute inset-0 z-20 pointer-events-none overflow-hidden text-slate-700",children:e.jsxs("div",{"data-testid":"main-menu-notebook",className:"pointer-events-auto absolute bottom-[5%] left-[6.5%] top-[max(96px,9.5%)] flex w-[30%] min-w-[320px] max-w-[620px] flex-col",children:[e.jsx("div",{className:"relative w-fit max-w-full transition-transform duration-500 hover:translate-x-1",children:e.jsx("img",{src:"/assets/local/branding/paper2galgame-logo.webp",alt:"Paper2Galgame","data-testid":"steam-home-logo",className:"h-auto w-[clamp(360px,32vw,620px)] max-w-[min(60vw,620px)] select-none drop-shadow-[0_3px_2px_rgba(255,255,255,.35)]",draggable:!1})}),e.jsx("nav",{"aria-label":n.mainMenu||"Main menu",className:"mt-[clamp(24px,3.5dvh,50px)] flex min-h-0 flex-1 w-[min(100%,460px)] flex-col items-start justify-evenly gap-y-[clamp(2px,.5dvh,8px)]",children:N.map(f=>e.jsx(qr.Fragment,{children:e.jsxs("button",{type:"button","aria-label":f.label,"data-testid":"main-menu-item",onClick:f.onClick,className:"group relative flex min-h-[clamp(42px,6.4dvh,68px)] w-full items-center justify-start rounded-sm px-[8%] py-[clamp(5px,.7dvh,10px)] text-left transition-all duration-300 hover:bg-transparent focus-visible:bg-transparent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#a35d7e]/60",children:[e.jsx("span",{className:"pointer-events-none absolute inset-x-[-5%] inset-y-1 z-0 scale-[.98] rounded-[2px] bg-[#fffaf0]/55 opacity-0 shadow-[0_0_18px_rgba(255,250,240,.2)] transition-all duration-300 ease-out group-hover:scale-100 group-hover:opacity-100 group-focus-visible:scale-100 group-focus-visible:opacity-100","aria-hidden":"true"}),e.jsx("span",{className:"pointer-events-none absolute left-0 top-1/2 z-10 h-px w-[11%] origin-left scale-x-0 bg-[#b58a78]/80 transition-transform duration-500 ease-out group-hover:scale-x-100 group-focus-visible:scale-x-100","aria-hidden":"true"}),e.jsx("span",{className:"pointer-events-none absolute left-[7%] top-1/2 z-20 h-[clamp(5px,.42vw,8px)] w-[clamp(5px,.42vw,8px)] -translate-y-1/2 rotate-45 scale-75 bg-[#a35d7e] opacity-0 transition-all duration-300 ease-out group-hover:scale-100 group-hover:opacity-100 group-focus-visible:scale-100 group-focus-visible:opacity-100","aria-hidden":"true"}),e.jsx("span",{className:"pointer-events-none absolute left-[12%] right-0 top-[calc(50%+clamp(17px,2.7dvh,26px))] z-10 h-px origin-left scale-x-0 bg-[#c4ad94]/80 transition-transform duration-500 ease-out group-hover:scale-x-100 group-focus-visible:scale-x-100","aria-hidden":"true"}),e.jsxs("span",{"data-p2g-tutorial":f.tutorialId,"data-p2g-tutorial-placement":f.tutorialId?"homepage-menu":void 0,className:"relative z-20 flex items-center gap-[clamp(10px,1vw,18px)] whitespace-nowrap bg-transparent px-3 font-serif text-[clamp(22px,2vw,36px)] font-semibold leading-none tracking-[.16em] text-[#40586a] transition-colors duration-300 group-hover:text-[#9c6176] group-focus-visible:text-[#9c6176]",children:[e.jsx(f.icon,{"aria-hidden":"true",size:"1em",strokeWidth:1.55,className:"shrink-0 opacity-75 transition-transform duration-300 ease-out group-hover:-translate-y-0.5 group-hover:rotate-[-8deg] group-hover:scale-110 group-focus-visible:-translate-y-0.5 group-focus-visible:rotate-[-8deg] group-focus-visible:scale-110"}),f.label]})]})},f.label))}),e.jsx("div",{className:"mt-auto flex w-[72%] items-center justify-center whitespace-nowrap border-t border-[#c4ad94]/70 pb-1 pt-3 text-[clamp(12px,.75vw,16px)] font-medium tracking-[.16em] text-[#83877f]",children:e.jsx("button",{type:"button","data-testid":"main-menu-item",onClick:w,className:"whitespace-nowrap transition-colors hover:text-[#9c6176]",children:n.about||"社群与作者"})})]})})},gi={zh:{close:"关闭",imports:"导入内容",importFile:"导入资料",document:"文档",video:"视频",moreSources:"其他入口",options:"附加功能",optionsHint:"按需开启",wechat:"微信",previewQr:"预览微信二维码",closeQr:"关闭微信二维码预览",qrAlt:"微信二维码",xiaohongshu:"小红书",douyin:"抖音",follow:"关注作者,获取最新动态",qqGroup:"QQ 交流群",copyQq:"复制群号",copied:"QQ群号已复制",copyFailed:"复制失败,请手动复制群号:1087093580"},en:{close:"Close",imports:"Import content",importFile:"Choose file",document:"Document",video:"Video",moreSources:"Other ways to play",options:"Additional options",optionsHint:"Enable as needed",wechat:"WeChat",previewQr:"Preview WeChat QR",closeQr:"Close WeChat QR preview",qrAlt:"WeChat QR code",xiaohongshu:"Xiaohongshu",douyin:"Douyin",follow:"Follow the author for updates",qqGroup:"QQ group",copyQq:"Copy group number",copied:"QQ group number copied",copyFailed:"Could not copy. Please copy the group number manually: 1087093580"},ja:{close:"閉じる",imports:"コンテンツのインポート",importFile:"ファイルを選択",document:"文書",video:"動画",moreSources:"その他の方法",options:"追加機能",optionsHint:"必要な場合のã
1¿æœ‰åŠ¹åŒ–",wechat:"WeChat",previewQr:"WeChat QRコードを表示",closeQr:"WeChat QRコードのプレビューを閉じる",qrAlt:"WeChat QRコード",xiaohongshu:"小紅書",douyin:"抖音",follow:"作者をフォローして最新情報をチェック",qqGroup:"QQグループ",copyQq:"グループ番号をコピー",copied:"QQグループ番号をコピーしました",copyFailed:"コピーできませんでした。グループ番号を手動でコピーしてください:1087093580"},ru:{close:"Закрыть",imports:"Импорт материалов",importFile:"Выбрать файл",document:"Документ",video:"Видео",moreSources:"Другие способы",options:"Дополнительные функции",optionsHint:"Включайте по мере необходимости",wechat:"WeChat",previewQr:"Показать QR-код WeChat",closeQr:"Закрыть QR-код WeChat",qrAlt:"QR-код WeChat",xiaohongshu:"Xiaohongshu",douyin:"Douyin",follow:"Подпишитесь на новости автора",qqGroup:"Группа QQ",copyQq:"Скопировать номер группы",copied:"Номер группы QQ скопирован",copyFailed:"Не удалось скопировать. Скопируйте номер группы вручную: 1087093580"}},ki=o=>gi[o],po={zh:{story:{title:"剧情模式",description:"把资料生成可游玩的视觉小说剧情。"},paper_qa:{title:"自由模式",description:"先阅读资料,再自由提问。"},study_room:{title:"Lofi 自习室",description:"专注学习,不需要 AI、材料或角色。"},startResearch:"开始自由模式",enterStudyRoom:"进入自习室",researchFileRequired:"请先上传研究资料。",researchVideoUnavailable:"自由模式仅支持文本和文档,不能使用视频链接。",modeNotConnected:"该模式入口尚未接入。"},en:{story:{title:"Story mode",description:"Turn your material into a playable visual novel."},paper_qa:{title:"Free mode",description:"Read your material, then ask questions freely."},study_room:{title:"Lofi study room",description:"Focus without AI, material, or a character."},startResearch:"Start Free mode",enterStudyRoom:"Enter study room",researchFileRequired:"Upload a research document first.",researchVideoUnavailable:"Free mode supports text and documents only; video links are not available.",modeNotConnected:"This mode entry is not connected yet."},ja:{story:{title:"ストーリーモード",description:"資料を遊べるビジュアルノベルにします。"},paper_qa:{title:"フリーモード",description:"資料を読んで、自由に質問できます。"},study_room:{title:"Lofi 自習室",description:"AI・資料・キャラクターなしで集中できます。"},startResearch:"フリーモードを開始",enterStudyRoom:"自習室へ",researchFileRequired:"先に資料をアップロードしてください。",researchVideoUnavailable:"フリーモードはテキストと文書のみ対応します。動画リンクは使えません。",modeNotConnected:"このモードの入口はまだ接続されていません。"},ru:{story:{title:"Сюжетный режим",description:"Превратите материалы в игровую визуальную новеллу."},paper_qa:{title:"Свободный режим",description:"Сначала изучите материалы, затем задавайте вопросы."},study_room:{title:"Lofi-кабинет",description:"Сосредоточьтесь без ИИ, материалов и персонажа."},startResearch:"Начать свободный режим",enterStudyRoom:"В кабинет",researchFileRequired:"Сначала загрузите материал для исследования.",researchVideoUnavailable:"Свободный режим поддерживает только текст и документы; видео недоступно.",modeNotConnected:"Вход в этот режим ещё не подключён."}};function wi(o){return po[o]||po.en}const vi=o=>{const n=o.file;return{text:n?"":o.text,fileName:o.fileName||(n==null?void 0:n.name)||"arxiv-paper.txt",uploadFiles:n?[n]:[],isArxivText:!n,loadedCharacterId:null,pendingSource:null}},Xt=500*1024,Ao=20,uo=16e3,yi=.15,xo=o=>o>Ao+yi,Ni=()=>Array.from({length:30},()=>{const o=Math.random()*100,n=10+Math.random()*15,b=Math.random()*15,h=10+Math.random()*15,g=(Math.random()-.5)*50,k=360+Math.random()*720,x=.5+Math.random()*.8;return{left:`${o}%`,width:`${h}px`,height:`${h*1.2}px`,animationDuration:`${n}s`,animationDelay:`-${b}s`,"--end-x":`${g}vw`,"--end-rot":`${k}deg`,"--end-scale":x}}),Si=o=>Number.isFinite(o)?`${o.toFixed(1)}s`:"0.0s",Ri=o=>{const n=Math.max(1,o.numberOfChannels),b=new Float32Array(o.length);for(let h=0;h<n;h+=1){const g=o.getChannelData(h);for(let k=0;k<g.length;k+=1)b[k]+=g[k]/n}return b},Ai=(o,n,b)=>{if(n===b)return o;const h=Math.max(1,Math.round(o.length*b/n)),g=new Float32Array(h),k=o.length/h;for(let x=0;x<h;
1x+=1){const w=x*k,v=Math.floor(w),m=Math.min(v+1,o.length-1),y=w-v;g[x]=o[v]*(1-y)+o[m]*y}return g},ji=(o,n)=>{const g=new ArrayBuffer(44+o.length*2),k=new DataView(g),x=(v,m)=>{for(let y=0;y<m.length;y+=1)k.setUint8(v+y,m.charCodeAt(y))};x(0,"RIFF"),k.setUint32(4,36+o.length*2,!0),x(8,"WAVE"),x(12,"fmt "),k.setUint32(16,16,!0),k.setUint16(20,1,!0),k.setUint16(22,1,!0),k.setUint32(24,n,!0),k.setUint32(28,n*2,!0),k.setUint16(32,2,!0),k.setUint16(34,16,!0),x(36,"data"),k.setUint32(40,o.length*2,!0);let w=44;for(let v=0;v<o.length;v+=1,w+=2){const m=Math.max(-1,Math.min(1,o[v]));k.setInt16(w,m<0?m*32768:m*32767,!0)}return new Blob([k],{type:"audio/wav"})},Wi=({onStart:o,onLoadScript:n,isLoading:b,onOpenSettings:h,characterId:g,setCharacterId:k,selectedDefaultSkinId:x,onSelectDefaultSkin:w,gameUiPreset:v,language:m,customCharacters:y,setCustomCharacters:N,user:f,onLogin:j,onLogout:H,onRefreshUser:ke,onOpenSaves:Q,onLoadSave:K,playerNickname:R,setPlayerNickname:$,onOpenCommunity:P,onOpenArxiv:O,voiceModeEnabled:Y,setVoiceModeEnabled:pe,onOpenMembership:te,onOpenProfile:Me,onOpenStudyDashboard:Ce,onStartResearch:we,onOpenStudyRoom:Oe,onOpenDocs:ue,arxivPrefill:S,onConsumeArxivPrefill:U,extensionFile:re,onClearExtensionFile:xe,extensionAutoStart:Ye,narrativeStyle:$e,setNarrativeStyle:bt})=>{var Os,$s,Ts,Es,Is,Us,_s,Ps,Fs,zs,Bs,Ds,Vs,Ws,Gs,qs,Hs;const c=ho(),Qe=Hr(),{width:ve,height:ye}=Yr(),{chars:B,loading:Te}=Qr(),[Ee,ta]=d.useState(""),[Ie,gt]=d.useState(null),[Ue,kt]=d.useState([]),[Fa,wt]=d.useState(!1),[jo,ae]=d.useState(!1),[D,Lo]=d.useState("story"),[Ke,vt]=d.useState("document"),[aa,ne]=d.useState(!1),[Mo,za]=d.useState(!1),[Co,sa]=d.useState(null),[Oo,Ba]=d.useState(!1),[$o,Xe]=d.useState(!1),[To,oa]=d.useState(!1),[Eo,_e]=d.useState(!1),[Da,yt]=d.useState(!1),[V,Va]=d.useState(null),[Je,ra]=d.useState(""),[Ze,na]=d.useState(""),[Nt,ia]=d.use
1State(""),[Ne,la]=d.useState(""),[et,da]=d.useState(!1),[tt,St]=d.useState({}),[Rt,At]=d.useState([]),[jt,ca]=d.useState(!1),[ma,pa]=d.useState(""),[F,Wa]=d.useState(null),[W,Pe]=d.useState(null),[at,ua]=d.useState(null),[st,Se]=d.useState(0),[ot,Re]=d.useState(0),[Z,Lt]=d.useState(0),[Ga,Mt]=d.useState(!1),[qa,X]=d.useState(null),[Io,xa]=d.useState([]),[Uo,ha]=d.useState(!1),[_o,rt]=d.useState(0),fa=d.useRef(null),nt=d.useRef(null),[ba,ee]=d.useState(null),[se,Ct]=d.useState(null),[Ha,ga]=d.useState(null),[Po,Ot]=d.useState({}),[Ya,$t]=d.useState([]),[Qa,Tt]=d.useState([]),[Li,ka]=d.useState(null),[wa,Fo]=d.useState(""),[Ka,Fe]=d.useState(!1),[Et,Xa]=d.useState(""),[It,Ja]=d.useState(!1),[L,Ut]=d.useState(null),[ze,Za]=d.useState(!1),[zo,_t]=d.useState(!1);d.useEffect(()=>()=>{at&&URL.revokeObjectURL(at)},[at]),d.useEffect(()=>{if(nt.current=null,xa([]),!F){ha(!1);return}const t=window.AudioContext||window.webkitAudioContext;if(!t)return;let a=!1;const r=new t;return ha(!0),(async()=>{try{const u=await r.decodeAudioData(await F.arrayBuffer());if(a)return;nt.current=u,xa(li(Array.from({length:u.numberOfChannels},(l,i)=>u.getChannelData(i)))),Lt(u.duration),Se(0),Re(Math.min(u.duration,15))}catch(u){a||console.error("Build voice waveform failed",u)}finally{a||ha(!1),r.close().catch(()=>{})}})(),()=>{a=!0}},[F]);const[it,es]=d.useState(""),[va,ts]=d.useState(!1),[as,lt]=d.useState(!1),[dt,Mi]=d.useState(!1),[Pt,Bo]=d.useState(!1),Do=!1,[Ft,Be]=d.useState(""),ya=d.useRef(!1),zt=d.useRef(null),ss=d.useRef(null),ct=d.useRef(null),[Vo,Na]=d.useState(!1),[oe,Wo]=d.useState(!1),[Go]=d.useState(Ni),s=Kr[m],Ae=wi(m);d.useEffect(()=>{!F||!xo(Z)||W===F&&(Pe(null),X(s.charVoiceRefAudioTooLong||"参考音频不能超过 20 秒,请先裁剪。"))},[s,Z,W,F]);const qo=((Os=f==null?void 0:f.name)==null?void 0:Os.trim())||(($s=f==null?void 0:f.email)==null?void 0:$s.split("@")[0])||"Player",Ho=(Ts=L==null?void 0:L.membership)!=null&&Ts.unlimitedAll?"Infinity":(Es=L==null?void 0:L.membership)!=null&&Es.active?((Is=L==null?void 0:L.membership)==null?void 0:Is.tier)==="basic"?"Basic":"Pro":m==="zh"?"普通用户":m==="ja"?"一般ユーザー":m==="ru"?"Обычный аккаунт":"Free",De={zh:{title:"Steam 版现已推出",features:"Live2D 角色、联机自习室、自定义 API",cta:"立即体验"},en:{title:"Now available on Steam",features:"Live2D characters, multiplayer study rooms, custom API",cta:"Try now"},ja:{title:"Steam 版配信開始",features:"Live2D キャラクター、オンライン自習室、カスタム API",cta:"今すぐ体験"},ru:{title:"Версия для Steam уже доступна",features:"Live2D-персонажи, совместные комнаты, собственный API",cta:"Попробовать"}}[m],Yo=!0,Bt=!!((Us=L==null?void 0:L.membership)!=null&&Us.active),os=!!((_s=L==null?void 0:L.membership)!=null&&_s.unlimitedAll);L!=null&&L.discordRewardClaimed||L!=null&&L.voiceCommunityViaRedemption;const rs=os?Number.MAX_SAFE_INTEGER:Bt?ea:1,Qo=os?m==="zh"?"Infinity 会员可同时上传任意数量文档,仍需满足单文件大小与格式要求。":"Infinity members can upload any number of documents; per-file size and format rules still apply.":Bt?s.uploadSubMember||s.uploadSub:s.uploadSubFree||s.uploadSub,{showAlert:A,showConfirm:mt}=Xr(),E=ki(m),ns=!ya.current,Ko=c?{paddingTop:"max(0px, env(safe-area-inset-top))",paddingRight:"max(0px, env(safe-area-inset-right))",paddingBottom:"max(0px, env(safe-area-inset-bottom))",paddingLeft:"max(0px, env(safe-area-inset-left))"}:void 0,je=c?{paddingTop:"max(0.5rem, env(safe-area-inset-top))",paddingRight:"max(0.5rem, env(safe-area-inset-right))",paddingBottom:"max(0.5rem, env(safe-area-inset-bottom))",paddingLeft:"max(0.5rem, env(safe-area-inset-left))"}:void 0,he=c?{WebkitOverflowScrolling:"touch",touchAction:"auto"}:void 0,is=ni({viewportWidth:ve,viewportHeight:ye,isMobileLayout:c,isPhoneLayout:Qe,showPromoBanner:Yo}),{isNearSquareMainMenu:Xo,shouldUseCompactMainMenu:G,shouldUseCompactMenuContent:Ve,compactMenuFrameWidth:Sa,compactMenuLogoWidth:Jo,compactMenuGap:Zo,compactMenuButtonPaddingY:ls,compactMenuButtonPaddingX:ds,compactMenuButtonMinHeight:cs,compactMenuIconSize:ms,compactMenuIconGap:er,compactMenuLabelSize:tr,compactMenuLabelLineHeight:ar,compactMenuSubLabelSize:sr,compactMenuSubLabelLineHeight:or,compactMenuTextGap:rr,compactMenuDividerInset:ps,compactMenuDividerMarginY:us,compactMenuContentPaddingTop:xs,compactMenuContentPaddingLeft:nr,compactMenuContentPaddingRight:hs,compactMenuContentPaddingBottom:ir,compactMenuRowExtent:fs,compactMenuNavHeight:bs,desktopMenuWidth:lr,characterStageLeft:dr,characterStageRight:cr}=is,ie=!c&&!Qe&&ve>=1024&&ye>=640,mr=G?{width:`${Sa}px`,gap:`${Zo}px`}:void 0,pr=G?{height:`${bs}px`,flex:"none"}
1:void 0,ur=G?{height:`${fs}px`,minHeight:`${fs}px`}:void 0,xr=G?{boxSizing:"border-box",width:"94%",height:`${cs}px`,minHeight:`${cs}px`,maxWidth:"94%",flexShrink:0,overflow:"hidden",paddingTop:`${ls}px`,paddingBottom:`${ls}px`,paddingLeft:`${ds}px`,paddingRight:`${ds}px`}:void 0,hr=G?{gap:`${rr}px`,minWidth:0,maxWidth:"100%",overflow:"hidden"}:void 0,fr=G?{width:`${ms}px`,height:`${ms}px`,marginRight:`${er}px`}:void 0,br=G?{flexShrink:0,fontSize:`${tr}px`,lineHeight:`${ar}px`,letterSpacing:Sa<330?"0.1em":"0.14em",whiteSpace:"nowrap"}:void 0,gr=G?{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",fontSize:`${sr}px`,lineHeight:`${or}px`,letterSpacing:Sa<330?"0.1em":"0.18em",whiteSpace:"nowrap"}:void 0,kr=G?{marginLeft:`${ps}px`,marginTop:`${us}px`,marginBottom:`${us}px`,width:`calc(100% - ${ps+hs+24}px)`,animationDelay:"calc(var(--animation-delay, 0s) + 0.1s)"}:void 0,wr=G?{boxSizing:"border-box",height:`calc(100% - ${xs+ir}px)`,marginTop:`${xs}px`,paddingLeft:`${nr}px`,paddingRight:`${hs}px`}:void 0,gs=t=>ii(t,is),[le,pt]=d.useState(ge),[ks,vr]=d.useState(null),yr=G?{width:`${Jo}px`,maxWidth:"none",opacity:0,animation:"titleFadeUp 0.6s ease-out forwards",animationDelay:"0.6s"}:void 0,ws={...G?he:void 0,scrollbarWidth:G?"thin":"none",...G?void 0:{msOverflowStyle:"none"}},Le=`absolute inset-0 flex items-center justify-center bg-black/40 backdrop-blur-sm animate-fade-in ${c?"p-1.5 overflow-hidden":"p-4"}`,ut="w-full bg-[#fffdfd] backdrop-blur-xl shadow-[0_20px_60px_rgba(0,0,0,0.3)] ring-pink-200",Nr=c?{maxHeight:"calc(var(--app-vh, 100dvh) * 0.9)"}:void 0;d.useEffect(()=>{Fo(Yn())},[]),d.useEffect(()=>{},[Y,pe]),d.useEffect(()=>{if(!re||!xe)return;const t=re,a=!!Ye;if(a||ae(!0),t.size>Ro){A(s.fileTooLarge||"File size exceeds 30MB limit.",{variant:"warning"}),xe();return}kt([t]),gt(t.name),ka(null),wt(!1),xe(),a&&o("",wa||"unknown_device",!0,!0,!1,!1,void 0,[t])},[re,xe,Ye,wa]),d.useEffect(()=>{if(!S)return;const t=vi(S);ta(t.text),Be(""),gt(t.fileName),kt(t.uploadFiles),ka(t.loadedCharacterId),wt(t.isArxivText),ae(!0),U()},[S,U]);const Dt=()=>{if(!f){Ut(null);return}const t=localStorage.getItem("p2g_token");if(!t){H();return}Ma("/api/user/status",{headers:{Authorization:`Bearer ${t}`}}).then(a=>{if(a.status===401)throw H(),new Error("Unauthorized");return a.json()}).then(a=>{typeof a.remaining=="number"&&(Ut(a),a.voiceUsedToday&&pe(!1))}).catch(a=>{a.message!=="Unauthorized"&&console.error("Failed to fetch status",a)}),Ma("/api/user/profile",{headers:{Authorization:`Bearer ${t}`}}).then(a=>{if(a.status===401)throw H(),new Error("Unauthorized");return a.json()}).then(a=>{a&&a.email===f.email&&(a.playerNickname&&!R&&($(a.playerNickname),localStorage.setItem("p2g_playerNickname",a.playerNickname)),(a.totalPlayTime!==f.totalPlayTime||a.totalPlayCount!==f.totalPlayCount||a.publicBadgeId!==f.publicBadgeId)&&ke({...f,...a}))}).catch(a=>{a.message!=="Unauthorized"&&console.error("Failed to sync profile stats",a)})},Sr=async()=>{if(!f){await A(s.steamWishlistLoginHint||"请先登录后领取 Steam 愿望单奖励。",{variant:"info"}),j();return}if(ze)return;Za(!0);const t=window.open("about:blank","_blank"),a=()=>{if(t&&!t.closed)try{t.location.replace(Ua);return}catch{}window.open(Ua,"_blank","noopener,noreferrer")};try{const r=localStorage.getItem("p2g_token");if(!r){t==null||t.close(),await A(s.steamWishlistLoginHint||"请先登录后领取 Steam 愿望单奖励。",{variant:"info"}),j();return}const u=await fetch("/api/steam/wishlist-reward",{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),l=await u.json().catch(()=>({}));if(u.ok)Ut(i=>i&&{...i,permanentUseBalance:typeof(l==null?void 0:l.permanentUseBalance)=="number"?l.permanentUseBalance:i.permanentUseBalance,permanentVoiceBalance:typeof(l==null?void 0:l.permanentVoiceBalance)=="number"?l.permanentVoiceBalance:i.permanentVoiceBalance,steamWishlistRewardClaimed:!0}),_e(!1),Dt(),a(),await A((l==null?void 0:l.message)||s.steamWishlistRewardSuccess||"感谢支持 Steam 愿望单,已发放 10 次永久使用次数和 3 次永久语音次数。",{variant:"success"});else if(u.status===409&&(l==null?void 0:l.code)==="STEAM_WISHLIST_REWARD_ALREADY_CLAIMED")Ut(i=>i&&{...i,permanentUseBalance:typeof(l==null?void 0:l.permanentUseBalance)=="number"?l.permanentUseBalance:i.permanentUseBalance,permanentVoiceBalance:typeof(l==null?void 0:l.permanentVoiceBalance)=="number"?l.permanentVoiceBalance:i.permanentVoiceBalance,steamWishlistRewardClaimed:!0}),_e(!1),Dt(),a(),await A((l==null?void 0:l.error)||s.steamWishlistRewardClaimed||"Steam 愿望单奖励已领取过",{variant:"info"});else if(u.status===401){t==null||t.close(),await A(s.steamWishlistLoginHint||"请先登录后领取 
1Steam 愿望单奖励。",{variant:"info"}),j();return}else{t==null||t.close(),await A((l==null?void 0:l.error)||s.redeemFailed||"领取失败,请稍后重试",{variant:"error"});return}}catch(r){t==null||t.close(),await A((r==null?void 0:r.message)||s.redeemFailed||"领取失败,请稍后重试",{variant:"error"})}finally{Za(!1)}};d.useEffect(()=>{Dt()},[f==null?void 0:f.id]),d.useEffect(()=>{const t=()=>{f&&Dt()};return window.addEventListener("focus",t),()=>window.removeEventListener("focus",t)},[f==null?void 0:f.id]),d.useEffect(()=>{const t=()=>_e(!0);return window.addEventListener("p2g-open-steam-wishlist-modal",t),()=>window.removeEventListener("p2g-open-steam-wishlist-modal",t)},[]),d.useEffect(()=>{aa||sa(null)},[aa]);let We=((Fs=La(B[0],g===((Ps=B[0])==null?void 0:Ps.id)?x:void 0))==null?void 0:Fs.avatarUrl)??((zs=B[0])==null?void 0:zs.avatarUrl)??"";const de=B.find(t=>t.id===g),ce=y.find(t=>t.id===g);de?We=((Bs=La(de,x))==null?void 0:Bs.avatarUrl)||de.avatarUrl:ce&&(We=ce.avatarUrl);const Vt=Oo?null:Jr(de||ce,!!de),Ge=`${g}:${Vt?"live2d":x||"default"}`,Rr=d.useCallback(()=>{Ba(!0)},[]);d.useEffect(()=>{Ba(!1)},[g,(Ds=de==null?void 0:de.live2d)==null?void 0:Ds.modelUrl,(Vs=ce==null?void 0:ce.live2d)==null?void 0:Vs.modelUrl]);const vs=(t,a)=>String(t||"").replace(/\{\{\s*name\s*\}\}/g,a),Ar=()=>{const t=B.find(r=>r.id===g);if(t){const r=s[t.waitingMessageKey]||"",u=qe(t);return vs(r,u)}const a=y.find(r=>r.id===g);if(a)return`${a.name} is waiting...`;if(B[0]){const r=s[B[0].waitingMessageKey]||"",u=qe(B[0]);return vs(r,u)}return""},qe=t=>{if(!t)return"";const a=t.names&&typeof t.names=="object"?t.names[m]:"";if(typeof a=="string"&&a.trim())return a.trim();const r=typeof t.name=="string"?t.name.trim():"";return r||s[t.nameKey]||t.id},ys=(()=>{const t=B.find(r=>r.id===g);if(t)return qe(t);const a=y.find(r=>r.id===g);return a?a.name:B[0]?qe(B[0]):""})()||"study partner",Wt=(t,a,r)=>{r.stopPropagation(),k(t),a&&w(t,a),za(!0)};d.useEffect(()=>{try{const t=localStorage.getItem(_a);if(!t){pt(ge);return}const a=JSON.parse(t),r=a==null?void 0:a[Ge];pt(r?gs({x:Number(r.x),y:Number(r.y),scale:Number(r.scale)}):ge)}catch{pt(ge)}finally{vr(Ge)}},[Ge,ve,ye]),d.useEffect(()=>{if(ks===Ge)try{const t=localStorage.getItem(_a),a=t?JSON.parse(t):{};a[Ge]=le,localStorage.setItem(_a,JSON.stringify(a))}catch{}},[Ge,ks,le]);const Ns=t=>{pt(a=>gs(typeof t=="function"?t(a):t))},jr=t=>{t.button!==0&&t.pointerType!=="touch"||(t.preventDefault(),t.currentTarget.setPointerCapture(t.pointerId),Na(!0),ct.current={pointerId:t.pointerId,startClientX:t.clientX,startClientY:t.clientY,startX:le.x,startY:le.y})},Lr=t=>{const a=ct.current;!a||a.pointerId!==t.pointerId||Ns({x:a.startX+(t.clientX-a.startClientX),y:a.startY+(t.clientY-a.startClientY),scale:le.scale})},Ss=t=>{var a;((a=ct.current)==null?void 0:a.pointerId)===t.pointerId&&(ct.current=null,Na(!1),t.currentTarget.hasPointerCapture(t.pointerId)&&t.currentTarget.releasePointerCapture(t.pointerId))},Rs=t=>{Ns(a=>({...a,scale:a.scale+t}))},Mr=()=>{ct.current=null,Na(!1),pt(ge)},Cr=async t=>{const a=t.target.files;if(!a||a.length===0)return;if(pi(a,rs)){const u=Bt?s.tooManyFiles||`最多只能上传 ${ea} 个文件。`:s.multiUploadMembersOnly||"普通用户一次只能上传 1 个文件,多文档上传为会员专享。";await A(u,{variant:"warning"}),t.target.value="";return}const r=mi(a,rs);if(ui(r)){await A(s.fileTooLarge||"File size exceeds 30MB limit.",{variant:"warning"}),t.target.value="";return}kt(r),vt("document"),Be(""),ta(""),gt(xi(r,m)),ka(null),wt(!1),t.target.value=""},Or=t=>{var u;const a=(u=t.target.files)==null?void 0:u[0];if(!a)return;ga(a);const r=new FileReader;r.onload=l=>{var i;la((i=l.target)==null?void 0:i.result)},r.readAsDataURL(a)},$r=(t,a)=>{var l;const r=(l=t.target.files)==null?void 0:l[0];if(!r)return;Ot(i=>({...i,[a]:r})),$t(i=>i.filter(p=>p!==a));const u=new FileReader;u.onload=i=>{St(p=>{var M;return{...p,[a]:(M=i.target)==null?void 0:M.result}})},u.readAsDataURL(r)},Tr=t=>{St(a=>{const r={...a};return delete r[t],r}),Ot(a=>{const r={...a};return delete r[t],r}),$t(a=>a.includes(t)?a:[...a,t])},As=async(t,a)=>{var l;const r=(l=t.target.files)==null?void 0:l[0];if(!r)return;if(r.size>5*1024*1024){await A(s.endingCgTooLarge||"CG image size must be 5MB or less",{variant:"warning"}),t.target.value="";return}if(!r.type.startsWith("image/")){await A(s.uploadImageFileOnly||"Please upload an image file",{variant:"warning"}),t.target.value="";return}const u=new FileReader;u.onload=i=>{var M;const p=(M=i.target)==null?void 0:M.result;At(_=>{const C=[..._];return typeof a=="number"&&a>=0&&a<C.length?C[a]=p:C.length<3&&C.push(p),C.slice(0,3)}),Tt(_=>{const C=[..._];return typeof a=="number"&&a>=0&&a<C.length?C[a]=r:C.length<3&&C.push(r),C.slice(0,3)})}
1,u.readAsDataURL(r),t.target.value=""},Er=t=>{At(a=>a.filter((r,u)=>u!==t)),Tt(a=>a.filter((r,u)=>u!==t))},Ir=async()=>{if(Et){if(!f){await A(s.loginRequired,{variant:"info"}),Fe(!1),j();return}Ja(!0);try{const t=localStorage.getItem("p2g_token"),a=await fetch("/api/user/characters/borrow",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({uuid:Et})}),r=await a.json();if(!a.ok)throw new Error(r.error||"Borrow failed");const u={dbId:r.id??r.dbId,id:r.characterId,name:r.name,prompt:r.prompt,performanceProfile:r.performanceProfile??void 0,avatarUrl:r.avatarUrl,renderMode:r.renderMode,live2d:r.live2d,cgImages:Array.isArray(r.cgImages)?r.cgImages:[],isBorrowed:!0,isShared:r.isShared,borrowId:r.borrowId,borrowCount:r.borrowCount,voiceRefAudioUrl:r.voiceRefAudioUrl??void 0,voiceRefText:r.voiceRefText??void 0,synthesisVersion:r.synthesisVersion??void 0,layout:r.layout??void 0,expressions:Xs(r)};N(l=>[...l.filter(p=>p.id!==u.id),u]),Fe(!1),Xa(""),await A(s.borrowSuccess||"Character borrowed successfully!",{variant:"success"})}catch(t){await A(t.message,{variant:"error"})}finally{Ja(!1)}}},js=t=>{const a=t.split(","),r=a[0].match(/:(.*?);/)[1],u=atob(a[1]);let l=u.length;const i=new Uint8Array(l);for(;l--;)i[l]=u.charCodeAt(l);return new Blob([i],{type:r})},Ls=()=>{Wa(null),Pe(null),ua(null),Se(0),Re(0),Lt(0),Mt(!1),X(null),xa([]),rt(0),nt.current=null},Ur=t=>{if(ee(null),X(null),Wa(t),Pe(t&&t.size<=Xt?t:null),Lt(0),Se(0),Re(0),rt(0),!t){ua(null);return}ua(URL.createObjectURL(t)),t.size>Xt&&X(s.charVoiceRefTrimNeeded||"音频超过 500KB 或 20 秒,请先裁剪后再保存。")},_r=t=>{const a=t.currentTarget.duration;!Number.isFinite(a)||a<=0||(Lt(a),Se(0),Re(Math.min(a,15)))},Pr=async()=>{if(!F)return;const t=Math.max(0,Math.min(st,Z||st)),a=Math.max(t+.1,Math.min(ot,Z||ot));if(a<=t){X(s.charVoiceRefTrimInvalid||"结束时间必须大于开始时间。");return}if(a-t>Ao){X(s.charVoiceRefAudioTooLong||"参考音频不能超过 20 秒,请缩短裁剪范围。");return}Mt(!0),X(null);const r=window.AudioContext||window.webkitAudioContext;if(!nt.current&&!r){Mt(!1),X(s.charVoiceRefTrimUnsupported||"当前浏览器不支持音频裁剪。");return}let u=null;try{let l=nt.current;l||(u=new r,l=await u.decodeAudioData(await F.arrayBuffer()));const i=Math.max(0,Math.floor(t*l.sampleRate)),p=Math.min(l.length,Math.ceil(a*l.sampleRate)),M=Ri(l).slice(i,p),_=Ai(M,l.sampleRate,uo),C=ji(_,uo),T=F.name.replace(/\.[^.]+$/,"")||"voice-reference",fe=new File([C],`${T}-trimmed.wav`,{type:"audio/wav"});if(fe.size>Xt){Pe(null),X(s.charVoiceRefAudioTooBig||"参考音频不能超过 500KB。");return}Pe(fe),Se(t),Re(a),ee(null)}catch(l){console.error("Trim voice reference failed",l),Pe(null),X(s.charVoiceRefTrimFailed||"音频裁剪失败,请换一个 WAV 或 MP3 文件重试。")}finally{Mt(!1),u==null||u.close().catch(()=>{})}},Fr=async t=>{if(!(!t.dbId||!await mt(s.workshopSyncChoiceMessage||"角色已保存,是否将本次修改同步到创意工坊?同步后需要重新审核。",{title:s.workshopSyncChoiceTitle||"同步创意工坊",variant:"info",confirmText:s.workshopSyncNow||"同步到创意工坊",cancelText:s.workshopSyncLater||"以后再说"})))try{const r=localStorage.getItem("p2g_token"),u=await fetch("/api/community/update",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({characterDbId:t.dbId,layout:t.layout})});if(!u.ok){const l=await u.json().catch(()=>({}));throw new Error(l.error||"WORKSHOP_SYNC_FAILED")}N(l=>l.map(i=>i.dbId===t.dbId?{...i,communityStatus:"PENDING"}:i)),await A(s.updateSubmissionSuccess||"更新已提交!等待审核中。",{variant:"success"})}catch{await A(s.workshopSyncFailed||"角色已保存,但同步创意工坊失败,请稍后重试。",{variant:"error"})}},Ms=async t=>{var l;if(!Je||!Ze||!Nt||!Ne){ee(s.fillAllFields||"Please fill all fields");return}const a=Je.toLowerCase().startsWith("u_")?Je.toLowerCase():`u_${Je.toLowerCase()}`;if(!/^[a-z0-9_]+$/.test(a)){await A(s.idInvalid||"ID must be lowercase letters/numbers/underscore only",{variant:"warning"});return}if(B.some(i=>i.id.toLowerCase()===a)){await A(s.idConflictBuiltin||"ID conflicts with built-in characters",{variant:"error"});return}if(!V&&y.some(i=>i.id===a)){await A(s.idConflictCustom||"ID already exists",{variant:"error"});return}if(W&&W.size>Xt){ee(s.charVoiceRefAudioTooBig||"参考音频不能超过 500KB。"),await A(s.charVoiceRefAudioTooBig||"参考音频不能超过 500KB。",{variant:"error"});return}const r=W===F?Z:Math.max(0,ot-st);if(W&&xo(r)){const i=s.charVoiceRefAudioTooLong||"参考音频不能超过 20 秒,请先裁剪。";ee(i),X(i),await A(i,{variant:"error"});return}if(F&&!W){const i=s.charVoiceRefTrimNeeded||"音频超过 500KB 或 20 秒,请先裁剪后再保存。";ee(i),X(i),await A(i,{variant:"error"});return}
1if(!V&&!t){Ct({id:a,name:Ze,spriteUrl:Ne});return}ca(!0),ee(null);let u=null;try{const i=y.find(C=>C.id===V);let p=null;if(f){const C=localStorage.getItem("p2g_token");if(C){const T=new FormData;T.append("characterId",a),T.append("name",Ze),T.append("prompt",Nt),T.append("isShared",String(et));const fe=t||go(wo((i==null?void 0:i.id)||a));T.append("layout",JSON.stringify(fe)),Ha?T.append("avatar",Ha):Ne.startsWith("data:")&&T.append("avatar",js(Ne),"avatar.png"),Ks.forEach(q=>{var ja;const be=Po[q];be?T.append(q.toLowerCase(),be):(ja=tt[q])!=null&&ja.startsWith("data:")&&T.append(q.toLowerCase(),js(tt[q]),`${q}.png`)}),i!=null&&i.dbId&&Ya.length>0&&T.append("removedExpressions",JSON.stringify(Ya.map(q=>q.toLowerCase())));const Aa=Rt.filter((q,be)=>/^https?:\/\//i.test(q||"")&&!Qa[be]).slice(0,3);T.append("cgKeepUrls",JSON.stringify(Aa));let xt=1;Qa.forEach(q=>{q&&xt<=3&&(T.append(`cg${xt}`,q),xt+=1)}),T.append("voiceRefText",(ma||"").trim()),W&&T.append("voiceRefAudio",W);const Ys=i&&i.dbId?"PUT":"POST",Gr=i&&i.dbId?`/api/user/characters/${i.dbId}`:"/api/user/characters",Gt=await fetch(Gr,{method:Ys,headers:{Authorization:`Bearer ${C}`},body:T});if(!Gt.ok){const q=await Gt.text();let be="";try{be=((l=JSON.parse(q))==null?void 0:l.error)||""}catch{be=""}throw u=oo(m,Gt.status,be),new Error("CHARACTER_SAVE_REQUEST_FAILED")}p=await Gt.json()}}ca(!1);const M=(ma||"").trim(),_={dbId:p?p.id:void 0,id:p?p.characterId:a,name:Ze,prompt:Nt,performanceProfile:(p==null?void 0:p.performanceProfile)??(i==null?void 0:i.performanceProfile)??void 0,avatarUrl:p?p.avatarUrl:Ne,renderMode:(p==null?void 0:p.renderMode)??(i==null?void 0:i.renderMode),live2d:(p==null?void 0:p.live2d)??(i==null?void 0:i.live2d),cgImages:p?Array.isArray(p.cgImages)?p.cgImages:[]:Rt,isShared:p?p.isShared:et,borrowCount:p?p.borrowCount:0,communityStatus:(p==null?void 0:p.communityStatus)??(i==null?void 0:i.communityStatus),voiceRefAudioUrl:(p==null?void 0:p.voiceRefAudioUrl)??(i==null?void 0:i.voiceRefAudioUrl)??void 0,voiceRefText:p?p.voiceRefText??void 0:M||void 0,synthesisVersion:(p==null?void 0:p.synthesisVersion)??(i==null?void 0:i.synthesisVersion)??void 0,layout:(p==null?void 0:p.layout)??t??(i==null?void 0:i.layout),expressions:p?Xs(p):tt};N(V?y.map(C=>C.id===V?_:C):[...y,_]),yt(!1),Ra(),V&&(i==null?void 0:i.communityStatus)==="APPROVED"&&await Fr(_)}catch(i){ca(!1),console.error("Save character error",i),ee(u||(i instanceof TypeError?Kn(m):oo(m)))}},Ra=()=>{ra(""),na(""),ia(""),la(""),da(!1),Va(null),St({}),At([]),ga(null),Ot({}),$t([]),Tt([]),pa(""),Ls(),ee(null),lt(!1),Ct(null)},Cs=()=>{yt(!1),Ra()},zr=async(t,a)=>{if(a.stopPropagation(),await mt(s.deleteConfirm||"Are you sure you want to delete this character?",{variant:"warning"})){const u=y.find(l=>l.id===t);if(f){const l=localStorage.getItem("p2g_token");try{u!=null&&u.isBorrowed&&u.borrowId?await fetch(`/api/user/characters/borrow/${u.borrowId}`,{method:"DELETE",headers:{Authorization:`Bearer ${l}`}}):u!=null&&u.dbId&&await fetch(`/api/user/characters/${u.dbId}`,{method:"DELETE",headers:{Authorization:`Bearer ${l}`}})}catch(i){console.error("Failed to delete character",i)}}N(y.filter(l=>l.id!==t)),g===t&&k("RUKA")}},Br=(t,a)=>{a.stopPropagation();const r=y.find(u=>u.id===t);r&&(ga(null),Ot({}),$t([]),ee(null),lt(!1),ra(r.id.replace(/^u_/,"")),na(r.name),ia(r.prompt??""),la(r.avatarUrl),da(!!r.isShared),St(r.expressions||{}),At(r.cgImages||[]),Tt([]),pa(r.voiceRefText??""),Ls(),Va(r.id),yt(!0))},Dr=()=>{Me()},Vr=async()=>{if(D==="study_room"){ae(!1),Oe?await Oe():await A(Ae.modeNotConnected,{variant:"info"});return}if(D==="paper_qa"){const l=Ft.trim(),i=!Ue.length&&Fa&&Ee.trim()?co(Ee,Ie||"arxiv-paper.txt"):null,p=Ue.length>0?Ue:i?[i]:void 0;if(l){await A(Ae.researchVideoUnavailable,{variant:"warning"});return}if(!p){await A(Ae.researchFileRequired,{variant:"warning"});return}if(!we){await A(Ae.modeNotConnected,{variant:"info"});return}ae(!1),await we({text:"",documentFiles:p});return}if(Te)return;if(b){await A(s.loadingScript||"正在生成中,请稍候...",{variant:"info"});return}const t=Ft.trim(),a=!Ue.length&&Fa&&Ee.trim()?co(Ee,Ie||"arxiv-paper.txt"):null,r=Ue.length>0?Ue:a?[a]:void 0;if(r&&t){await A(m==="zh"?"文档批次暂不支持与视频链接同时使用,请先清空视频链接。":"Document batches cannot be combined with a video URL. Please clear the video URL first.",{variant:"warning"});return}if(!r&&Ee.trim().length<=50&&!t){await A(s.contentTooShort,{variant:"warning"});return}if(t)try{const l=new URL(t);if(!["http:","https:"].includes(l.protocol))throw new Error("unsupported protocol")}catch{await A(m==="zh"?"请输入有效的 HTTP/HTTPS 视频链接。":"Please enter a valid HTTP/HTTPS video URL.",{variant:"warning"});return}if(!f){_t(!0);return}const u=Y&&!dt;if(u)try{const l=localStorage.getItem("p2g_token");if(!l){await A(s.loginRequired||"请先登录后使用该功能。",{variant:"info"});return}const i=await Ma("/api/tts/queue-info",{headers:{Authorization:`Bearer ${l}`},cache:"no-store"}),p=await i.json().catch(()=>({}));if(i.ok){const M=tn(p),_=an(M),C=Math.max(0,Number(p==null?void 0:p.queueLoad)||0),T=Math.max(1,Number(p==null?void 0:p.maxQueueSize)||10);if((p==null?void 0:p.isQueueFull)===!0||C>=T){const fe=s.ttsQueueFull||"当前语音排队人数已达上限({{max}} 人),请稍后再试。";await A(String(fe).replace(/\{\{max\}\}/g,String(T)),{variant:"warning"});return}if(_>0){const fe=Math.max(1,Math.ceil((M==null?void 0:M.etaMinutes)||_*sn)),Aa=s.tt
1sQueueConfirmBody||`当前语音排队人数:{{count}}
2预计等待时间:约 {{minutes}} 分钟
3
4是否继续开启语音模式进入游戏?`,xt=String(Aa).replace(/\{\{count\}\}/g,String(_)).replace(/\{\{minutes\}\}/g,String(fe));if(!await mt(xt,{variant:"warning"}))return}}else{const M=(p==null?void 0:p.error)||i.status,_=s.ttsQueueFetchFailedWithCodeConfirm||`暂时无法获取语音排队信息({{reason}})。
5是否仍然继续开启语音模式?`,C=String(_).replace(/\{\{reason\}\}/g,String(M));if(!await mt(C,{variant:"warning"}))return}}catch{const l=s.ttsQueueFetchFailedConfirm||"暂时无法获取语音排队信息,是否仍然继续开启语音模式?";if(!await mt(l,{variant:"warning"}))return}o(Ee,wa||"unknown_device",!0,!1,u,dt,r&&r.length>0?void 0:t||void 0,r,Pt&&!!(r!=null&&r.some(l=>/\.(pdf|docx|pptx|ppt)$/i.test(l.name))))},Wr=async()=>{if(it.trim()){ts(!0);try{const t=await fetch(`/api/public/saves/${it.trim()}`);if(!t.ok)throw t.status===404?new Error(s.saveNotFound||"存档不存在 (Save not found)"):t.status===403?new Error(s.saveNotShared||"该存档未分享 (Save not shared)"):new Error("Load failed");const a=await t.json();K(a),ae(!1),es("")}catch(t){await A(en(t==null?void 0:t.message,m),{variant:"error"})}finally{ts(!1)}}};d.useEffect(()=>{ya.current||(ya.current=!0)},[]),d.useEffect(()=>{zt.current&&(zt.current.scrollTop=0)},[bs,ve,ye,f==null?void 0:f.id]);const z=({label:t,subLabel:a,onClick:r,active:u=!1,introClass:l="",hasDivider:i=!0})=>e.jsxs("div",{className:"w-full min-w-0 shrink-0 snap-start overflow-hidden flex flex-col items-start",style:ur,children:[e.jsxs("button",{onClick:r,"data-testid":"main-menu-item",className:`
6                group relative min-w-0 text-left flex items-center transition-all duration-300 ease-out
7                ${Ve?"w-[94%] py-1.5 px-3 hover:translate-x-2":"w-[90%] py-2 px-8 hover:translate-x-4"}
8                ${ns?l:""}
9                `,style:xr,children:[e.jsx("div",{"data-testid":"main-menu-content",className:`flex items-center justify-center shrink-0 origin-center rotate-0 opacity-80 group-hover:opacity-100 group-hover:rotate-[48deg] transition-[opacity,transform] duration-500 ease-[cubic-bezier(0.34,1.45,0.64,1)] ${Ve?"w-4 h-4 mr-2":"w-5 h-5 mr-3"}`,"aria-hidden":!0,style:fr,children:e.jsx("img",{src:"/assets/local/branding/sakura2.png",alt:"",className:"w-full h-full object-contain drop-shadow-md pointer-events-none",loading:"lazy",decoding:"async"})}),e.jsxs("div",{className:"flex min-w-0 flex-col items-start",style:hr,children:[e.jsx("span",{"data-testid":"main-menu-content",className:`font-sans font-bold leading-tight whitespace-nowrap ${Ve?"text-[15px] tracking-[0.14em]":"text-xl md:text-2xl tracking-[0.16em]"} text-slate-700 group-hover:text-pink-600 transition-colors drop-shadow-sm`,style:br,children:t}),e.jsx("span",{"data-testid":"main-menu-content",className:`leading-none whitespace-nowrap ${Ve?"text-[11px]":"text-[11px] md:text-xs mt-0"} font-bold tracking-[0.22em] uppercase text-pink-400/80 group-hover:text-pink-500 transition-colors`,style:gr,children:a})]})]}),i&&e.jsx("div",{"data-testid":"main-menu-decoration",className:`h-px shrink-0 border-b-[1.5px] border-dashed border-pink-300/60 ${Ve?"w-[82%] ml-8 my-0.5":"w-[60%] ml-12 my-0.5"} ${ns?l:""}`,style:kr??{animationDelay:"calc(var(--animation-delay, 0s) + 0.1s)"}})]});return e.jsxs("div",{className:"absolute inset-0 w-full h-full bg-[#fff0f5] overflow-hidden font-sans select-none box-border",style:Ko,children:[e.jsx("style",{children:`
10                @keyframes fadeIn {
11                    from { opacity: 0; transform: translateY(6px) scale(0.98); }
12                    to { opacity: 1; transform: translateY(0) scale(1); }
13                }
14            `}),e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("img",{src:ie?"/assets/local/branding/homepage-v2-background.webp":"/background.jpg",alt:"Background Base","data-testid":ie?"steam-home-background":void 0,className:"absolute inset-0 w-full h-full object-cover object-center filter saturate-[1.1] contrast-[1.05]"}
14),!ie&&e.jsx("img",{src:"/background.jpg",alt:"Background Bloom",className:"absolute inset-0 w-full h-full object-cover object-center filter blur-[12px] brightness-[1.15] saturate-[1.2] mix-blend-screen opacity-40"}),!ie&&e.jsx("div",{className:"absolute inset-0 bg-white/10"})]}),e.jsxs("div",{className:`absolute inset-0 pointer-events-none overflow-hidden ${ie?"hidden":""}`,children:[e.jsx("style",{children:`
15                    .sakura-petal {
16                        position: absolute;
17                        background: linear-gradient(135deg, #ffb7c5 0%, #ff9ebd 100%);
18                        border-radius: 15px 0px 15px 0px;
19                        opacity: 0.8;
20                        box-shadow: 0 0 10px rgba(255, 183, 197, 0.4);
21                        animation: fall linear infinite;
22                    }
23                    @keyframes fall {
24                        0% {
25                            transform: translate(0, -10vh) rotate(0deg) scale(0.5);
26                            opacity: 0;
27                        }
28                        10% {
29                            opacity: 0.8;
30                        }
31                        90% {
32                            opacity: 0.6;
33                        }
34                        100% {
35                            transform: translate(var(--end-x), 110vh) rotate(var(--end-rot)) scale(var(--end-scale));
36                            opacity: 0;
37                        }
38                    }
39                    `}),Go.map((t,a)=>e.jsx("div",{className:"sakura-petal",style:t},`petal-${a}`))]}),e.jsxs("div",{className:"absolute inset-0 z-10 w-full h-full pointer-events-none",children:[e.jsx("a",{href:Xn,target:"_blank",rel:"noopener noreferrer",className:"absolute left-2 top-2 z-[60] flex h-11 w-[68%] max-w-[680px] translate-x-0 items-center overflow-hidden rounded-lg border border-pink-200 bg-white px-2.5 text-left shadow-[0_8px_24px_rgba(190,104,135,0.18)] transition hover:border-pink-300 hover:bg-pink-50 active:scale-[0.99] pointer-events-auto min-[640px]:left-1/2 min-[640px]:w-[48%] min-[640px]:-translate-x-1/2 sm:px-4 lg:top-3 lg:h-12 lg:w-[680px]","aria-label":`${De.title}:${De.features},${De.cta}`,children:e.jsxs("span",{className:"mx-auto flex w-full max-w-[1100px] items-center gap-2 sm:gap-3",children:[e.jsx("span",{className:"hidden h-8 w-8 shrink-0 items-center justify-center rounded-md border border-slate-200 bg-slate-900 min-[480px]:flex lg:h-9 lg:w-9",children:e.jsx("img",{src:ro,alt:"",className:"h-5 w-5 object-contain"})}),e.jsx("span",{className:"hidden shrink-0 text-xs font-black text-slate-700 min-[560px]:inline lg:text-sm",children:De.title}),e.jsx("span",{className:"hidden shrink-0 text-sm font-black text-pink-500 min-[560px]:inline","aria-hidden":"true",children:"→"}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-[10px] font-black text-slate-700 min-[480px]:text-xs sm:text-sm lg:text-base",children:De.features}),e.jsxs("span",{className:"flex shrink-0 items-center gap-1 text-[11px] font-black text-pink-600 sm:text-xs lg:text-sm",children:[e.jsx("span",{children:De.cta}),e.jsx(eo,{size:14})]})]})}),ie?e.jsx(bi,{language:m,translations:s,onStart:()=>ae(!0),onPartner:()=>ne(!0),onSaves:Q,onWorkshop:P,onMembership:te,onSettings:h,onCommunity:()=>Xe(!0),onDiscover:O,onStudyDashboard:void 0}):G?e.jsxs("div",{className:"absolute left-[2%] bottom-[2%] z-40 max-w-[820px] flex flex-col pointer-events-none top-[64px]",style:mr,children:[e.jsx("div",{className:"pointer-events-auto shrink-0 px-1.5",children:e.jsx("div",{className:"relative transition-transform duration-500 hover:scale-105 origin-top-left",children:e.jsx(Qt,{src:"/logo.webp",widths:[320,480,640,960,1280],sizes:"(max-width: 1024px) 90vw, 600px",alt:"Logo","data-testid":"main-menu-logo",className:"w-full max-w-[390px] h-auto object-contain filter drop-shadow-md",style:yr})})}),e.jsxs("div",{"data-testid":"main-menu-notebook",className:"relative z-30 pointer-events-auto transition-transform origin-left min-h-0 overflow-hidden",style:pr,children:[e.jsx("div",{className:"absolute inset-0 flex overflow-hidden pointer-events-none drop-shadow-2xl",children:e.jsx(Qt,{src:"/nav.webp",widths:[320,480,640,960,1120],sizes:"(max-width: 1024px) 82vw, 400px",alt:"Navigation Backgroun
39d",className:"w-full h-full object-fill opacity-95 md:opacity-100"})}),e.jsxs("div",{ref:zt,className:"relative z-20 flex min-w-0 flex-col gap-0 h-full snap-y snap-mandatory overflow-x-hidden overflow-y-auto overscroll-y-contain custom-scrollbar",style:{...ws,...wr},children:[e.jsx(z,{label:s.start||"开始游戏",subLabel:"START",onClick:()=>ae(!0),introClass:"menu-intro-1"}),e.jsx(z,{label:s.partner||"搭档",subLabel:"PARTNER",onClick:()=>ne(!0),introClass:"menu-intro-2"}),e.jsx(z,{label:s.saves||"存档",subLabel:"SAVES",onClick:Q,introClass:"menu-intro-3"}),e.jsx(z,{label:s.paperDiscoveryTitle,subLabel:"DISCOVER",onClick:O,introClass:"menu-intro-4"}),Qs,e.jsx(z,{label:s.communityTitle||"创意工坊",subLabel:"WORKSHOP",onClick:P,introClass:"menu-intro-5"}),e.jsx(z,{label:m==="zh"?"会员":"Membership",subLabel:"VIP",onClick:te,introClass:"menu-intro-6"}),e.jsx(z,{label:s.settings||"设置",subLabel:"CONFIG",onClick:h,introClass:"menu-intro-7"}),e.jsx(z,{label:s.about||"社群与作者",subLabel:"COMMUNITY",onClick:()=>Xe(!0),introClass:"menu-intro-8",hasDivider:!1})]})]}),e.jsx("style",{children:`
40                    @keyframes titleFadeUp {
41                        0% {
42                            opacity: 0;
43                            transform: translateY(18px);
44                        }
45                        100% {
46                            opacity: 1;
47                            transform: translateY(0);
48                        }
49                    }
50                    `})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"absolute left-[5%] z-40 pointer-events-auto top-[64px]",children:[e.jsx("div",{className:"relative transition-transform duration-500 hover:scale-105 origin-top-left",children:e.jsx(Qt,{src:"/logo.webp",widths:[320,480,640,960,1280],sizes:"(max-width: 1024px) 90vw, 600px",alt:"Logo","data-testid":"main-menu-logo",className:"w-[45vw] lg:w-[35vw] xl:w-[30vw] min-w-[260px] max-w-[600px] h-auto object-contain filter drop-shadow-md",style:{opacity:0,animation:"titleFadeUp 0.6s ease-out forwards",animationDelay:"0.6s"}})}),e.jsx("style",{children:`
51                    @keyframes titleFadeUp {
52                        0% {
53                            opacity: 0;
54                            transform: translateY(18px);
55                        }
56                        100% {
57                            opacity: 1;
58                            transform: translateY(0);
59                        }
60                    }
61                    `})]}),e.jsxs("div",{"data-testid":"main-menu-notebook",className:"absolute z-30 pointer-events-auto transition-transform origin-left top-[25%] left-[4%] bottom-[3%] min-w-[220px] max-w-[400px] overflow-hidden",style:{width:`${lr}px`},children:[e.jsx("div",{className:"absolute inset-0 flex overflow-hidden pointer-events-none drop-shadow-2xl",children:e.jsx(Qt,{src:"/nav.webp",widths:[320,480,640,960,1120],sizes:"(max-width: 1024px) 82vw, 400px",alt:"Navigation Background",className:"w-full h-full object-fill opacity-95 md:opacity-100"})}),e.jsxs("div",{ref:zt,className:"relative z-20 flex min-w-0 flex-col gap-0 h-full overflow-x-hidden overflow-y-auto overscroll-y-contain py-10 pl-6 [&::-webkit-scrollbar]:hidden",style:ws,children:[e.jsx(z,{label:s.start||"开始游戏",subLabel:"START",onClick:()=>ae(!0),introClass:"menu-intro-1"}),e.jsx(z,{label:s.partner||"搭档",subLabel:"PARTNER",onClick:()=>ne(!0),introClass:"menu-intro-2"}),e.jsx(z,{label:s.saves||"存档",subLabel:"SAVES",onClick:Q,introClass:"menu-intro-3"}),e.jsx(z,{label:s.paperDiscoveryTitle,subLabel:"DISCOVER",onClick:O,introClass:"menu-intro-4"}),Qs,e.jsx(z,{label:s.communityTitle||"创意工坊",subLabel:"WORKSHOP",onClick:P,introClass:"menu-intro-5"}),e.jsx(z,{label:m==="zh"?"会员":"Membership",subLabel:"VIP",onClick:te,introClass:"menu-intro-6"}),e.jsx(z,{label:s.settings||"设置",subLabel:"CONFIG",onClick:h,introClass:"menu-intro-7"}),e.jsx(z,{label:s.about||"社群与作者",subLabel:"COMMUNITY",onClick:()=>Xe(!0),introClass:"menu-intro-8",hasDivider:!1})]})]})]}),e.jsxs("div",{"data-testid":"main-menu-character-editor",className:`fixed z-30 pointer-events-auto flex items-center gap-2 rounded-2xl border border-white/60 bg-white/65 shadow-xl backdrop-blur-md ${c?"right-[72px] bottom-3 p-1":"right-6 bottom-6 px-2 py-2"}`,children:[e.jsx("button",{type:"button",onClick:()=>Wo(t=>
61!t),className:`${c?"h-11 w-11":"h-9 w-9"} flex items-center justify-center rounded-xl bg-slate-900/85 text-white transition hover:bg-slate-800 active:scale-95`,"aria-label":oe?"退出主页面立绘编辑模式":"进入主页面立绘编辑模式",title:oe?"退出编辑":"编辑立绘",children:e.jsx(gn,{size:16})}),oe&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>Rs(-.08),className:`${c?"h-11 w-11":"h-9 w-9"} flex items-center justify-center rounded-xl bg-slate-900/85 text-white transition hover:bg-slate-800 active:scale-95`,"aria-label":"缩小主页面立绘",title:"缩小立绘",children:e.jsx(vo,{size:16})}),e.jsxs("button",{type:"button",onClick:Mr,className:`${c?"h-11":"h-9"} flex min-w-[72px] items-center justify-center gap-1 rounded-xl bg-pink-500 px-3 text-xs font-black text-white transition hover:bg-pink-600 active:scale-95`,"aria-label":"重置主页面立绘位置和大小",title:"重置立绘",children:[e.jsx(yo,{size:14}),e.jsx("span",{children:`${Math.round(le.scale*100)}%`})]}),e.jsx("button",{type:"button",onClick:()=>Rs(.08),className:`${c?"h-11 w-11":"h-9 w-9"} flex items-center justify-center rounded-xl bg-slate-900/85 text-white transition hover:bg-slate-800 active:scale-95`,"aria-label":"放大主页面立绘",title:"放大立绘",children:e.jsx(ht,{size:16})})]})]}),e.jsx("div",{"data-testid":"main-menu-character-stage",className:"absolute inset-y-0 z-10 flex items-end justify-center overflow-hidden pointer-events-none",style:{left:ie?"55%":`${dr}px`,right:ie?"5%":`${cr}px`},children:e.jsx("div",{className:`flex h-full w-full items-end justify-center touch-none ${oe?"pointer-events-auto":"pointer-events-none"} ${Vo?"cursor-grabbing":oe?"cursor-grab":"cursor-default"}`,onPointerDown:oe?jr:void 0,onPointerMove:oe?Lr:void 0,onPointerUp:oe?Ss:void 0,onPointerCancel:oe?Ss:void 0,style:{transform:`translate3d(${le.x}px, ${le.y}px, 0) scale(${le.scale})`,transformOrigin:"bottom center"},title:oe?"拖拽调整立绘位置":void 0,children:e.jsx("div",{"data-testid":"main-menu-character",className:"flex h-full w-full items-end justify-center",style:{opacity:0,animation:"spriteFadeUp 2s cubic-bezier(0.22, 1, 0.36, 1) forwards"},children:Vt?e.jsx("div",{className:"h-full w-full object-bottom filter drop-shadow-2xl transition-all duration-500",children:e.jsx(ko,{config:Vt,emotion:fo.NEUTRAL,onError:Rr})}):bo(We)?e.jsx("video",{src:We,autoPlay:!0,loop:!0,muted:!0,playsInline:!0,className:"h-full w-auto max-w-full object-contain object-bottom filter drop-shadow-2xl transition-all duration-500"},g):e.jsx("img",{src:We,alt:`${ys} character illustration`,className:"h-full w-auto max-w-full object-contain object-bottom filter drop-shadow-2xl transition-all duration-500"},g)})})}),e.jsx("style",{children:`
62                    @keyframes spriteFadeUp {
63                        0% {
64                            opacity: 0;
65                            transform: translateY(36px) scale(0.9);
66                            filter: blur(4px);
67                        }
68                        60% {
69                            opacity: 1;
70                            transform: translateY(0) scale(1);
71                            filter: blur(0);
72                        }
73                        100% {
74                            opacity: 1;
75                            transform: translateY(0) scale(1);
76                            filter: blur(0);
77                        }
78                    }
79                    `}),e.jsx("div",{className:"absolute right-4 top-4 z-50 pointer-events-auto flex items-center gap-2",children:f?e.jsxs("button",{type:"button",onClick:Dr,className:`group/user relative flex min-w-0 items-center py-2 pl-4 pr-[64px] text-left transition active:scale-[0.98] animate-fade-in-up ${ie?"h-[68px] w-[218px]":Ve?"h-[60px] w-[min(64vw,165px)]":"h-[60px] w-[170px]"}`,title:f.email,children:[e.jsx("span",{"aria-hidden":"true",className:"absolute inset-y-[5px] left-0 right-8 rounded-xl border border-white bg-white shadow-[0_8px_24px_rgba(190,104,135,0.16)] transition group-hover/user:border-pink-200"}),e.jsxs("div",{className:"relative z-10 min-w-0 flex-1",children:[e.jsx("div",{className:`truncate text-sm font-bold leading-5 ${on((Ws=L==null?void 0:L.membership)==null?void 0:Ws.active,"text-slate-700",f.publicBadgeId,(Gs=L==null?void 0:L.membership)==null?void 0:Gs.unlimitedAll)}`,children:qo}),e.jsx("div",{className:"truncate text-xs font-semibold leading-4 text-slate-400",children:Ho})]}),e.jsx("img",{src:"/player-avatar.webp",alt:"",className:"absolute right-0 top-1/2 z-20 h-14 w-14 -translate-y-1/2 roun
79ded-full border-[3px] border-white object-cover shadow-md ring-2 ring-pink-200/80 transition-transform group-hover/user:scale-105"})]}):e.jsxs("button",{onClick:j,className:"group flex items-center gap-2 rounded-2xl border border-pink-200 bg-white/70 p-2 pr-3 text-slate-700 shadow-sm backdrop-blur-md transition-all hover:border-pink-300 hover:bg-white/90 hover:text-pink-600 active:scale-95 animate-fade-in-up",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-pink-50 text-pink-500 shadow-sm transition-transform group-hover:scale-105",children:e.jsx(Ca,{size:18,strokeWidth:3})}),e.jsx("span",{className:"text-sm font-black tracking-[0.12em]",children:s.login})]})}),e.jsx("style",{children:`
80                    @keyframes menuButtonSlideRight {
81                        0% {
82                            opacity: 0;
83                            transform: translateX(-40px);
84                        }
85                        100% {
86                            opacity: 1;
87                            transform: translateX(0);
88                        }
89                    }
90
91                    .menu-intro-1 {
92                        opacity: 0;
93                        animation: menuButtonSlideRight 0.6s cubic-bezier(0.22, 1, 0.36, 1) forwards;
94                        animation-delay: 0.4s;
95                    }
96                    .menu-intro-2 {
97                        opacity: 0;
98                        animation: menuButtonSlideRight 0.6s cubic-bezier(0.22, 1, 0.36, 1) forwards;
99                        animation-delay: 0.5s;
100                    }
101                    .menu-intro-3 {
102                        opacity: 0;
103                        animation: menuButtonSlideRight 0.6s cubic-bezier(0.22, 1, 0.36, 1) forwards;
104                        animation-delay: 0.6s;
105                    }
106                    .menu-intro-4 {
107                        opacity: 0;
108                        animation: menuButtonSlideRight 0.6s cubic-bezier(0.22, 1, 0.36, 1) forwards;
109                        animation-delay: 0.7s;
110                    }
111                    .menu-intro-5 {
112                        opacity: 0;
113                        animation: menuButtonSlideRight 0.6s cubic-bezier(0.22, 1, 0.36, 1) forwards;
114                        animation-delay: 0.8s;
115                    }
116                    .menu-intro-6 {
117                        opacity: 0;
118                        animation: menuButtonSlideRight 0.6s cubic-bezier(0.22, 1, 0.36, 1) forwards;
119                        animation-delay: 0.9s;
120                    }
121                    .menu-intro-7 {
122                        opacity: 0;
123                        animation: menuButtonSlideRight 0.6s cubic-bezier(0.22, 1, 0.36, 1) forwards;
124                        animation-delay: 1.0s;
125                    }
126                    .menu-intro-8 {
127                        opacity: 0;
128                        animation: menuButtonSlideRight 0.6s cubic-bezier(0.22, 1, 0.36, 1) forwards;
129                        animation-delay: 1.1s;
130                    }
131                    .menu-intro-9 {
132                        opacity: 0;
133                        animation: menuButtonSlideRight 0.6s cubic-bezier(0.22, 1, 0.36, 1) forwards;
134                        animation-delay: 1.2s;
135                    }
136                    `}),e.jsx("div",{className:`absolute bottom-3 z-20 pointer-events-none flex justify-center ${c?`${Xo?"left-[22%]":"left-[55%]"} -translate-x-1/2`:"right-[5%]"}`,children:e.jsx("span",{"data-testid":"main-menu-copyright",className:"whitespace-nowrap text-slate-600/60 text-[9px] md:text-[10px] font-bold tracking-widest bg-white/30 px-3 py-1 rounded-full backdrop-blur-sm border border-white/40",children:"©2025-2026 Paper2Gal"})})]}),jo&&e.jsxs("section",{"data-testid":"start-panel",role:"dialog","aria-modal":"true","aria-labelledby":"start-panel-title",className:"steam-start-panel",children:[e.jsx("div",{className:"steam-start-decoration","aria-hidden":"true"}),e.jsxs("header",{className:"steam-start-header",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{id:"start-panel-title",className:"font-black tracking-tighter text-brand-darkPink",children:s.topicSelect}),e.jsx("p",{className:"text-slate-500 font-medium",children:Ar()})]}),e.jsx("button",{type:"button","data-testid":"start-panel-close","aria-label":E.close,onClick:()=>ae(!1),className:"steam-surface-close",children:e.jsx(J,{size:24,strokeWidth:3})})]}),e.jsxs("div",{"data-testid":"start-panel-scroll",className:"steam-start-scroll custom-scrollbar",style:he,children:[e.jsx(fi,{mode:D,onModeChange:t=>{Lo(t),t==="paper_qa"&&(vt("document"),Be(""))},labels:Ae,className:"order-0 shrink-0"}),e.jsxs("div",{className:"steam-start-lower",children:[D==="story"&&e.jsxs("div",{"data-testid":"topic-mode-row",className:"steam-start-options",children:[e.jsxs("div",{className:"steam-start-options-heading",children:[e.jsx("h3",{className:"steam-section-title",children:E.options}),e.jsx("span",{children:E.optionsHint})]}),e.jsxs("div",{className:`flex items-stretch gap-2 md:gap-3 self-start ${c?"shrink-0 flex-nowrap":"flex-wrap"}`,children:[e.jsxs("div",{className:`flex items-center rounded-xl border border-violet-100 bg-violet-50/80 overflow-hidden ${c?"h-10 gap-2 px-2 py-1":"gap-3 px-4 py-2.5"}`,children:[e.jsxs("div",{className:`flex flex-col min-w-0 ${c?"max-w-[108px]":""}`,children:[e.jsx("span",{className:"truncate whitespace-nowrap text-[10px] font-black text-violet-600 uppercase tracking-widest leading-none",children:m==="zh"?"娱乐模式":m==="ja"?"娯æ¥
136½ãƒ¢ãƒ¼ãƒ‰":m==="ru"?"Развлекательный режим":"Fun Mode"}),e.jsx("span",{className:"truncate whitespace-nowrap text-[8px] text-slate-500 font-bold opacity-80 leading-tight",children:m==="zh"?"轻松有趣的剧情口吻":m==="ja"?"楽しく軽快なストーリー口調":m==="ru"?"Лёгкий и весёлый стиль":"Light and playful story tone"})]}),e.jsx("button",{type:"button","aria-pressed":$e==="lighthearted","aria-label":m==="zh"?"娱乐模式:开启后使用轻松娱乐口吻,关闭时保持经典原版":"Fun mode: use a light, playful tone when enabled and the classic style when disabled",onClick:()=>bt($e==="lighthearted"?"classic":"lighthearted"),className:"group relative h-11 w-11 shrink-0 focus-visible:outline-none",children:e.jsx("span",{className:`absolute inset-x-0 top-1/2 h-6 -translate-y-1/2 rounded-full border-2 transition-colors group-focus-visible:ring-2 group-focus-visible:ring-violet-300 ${$e==="lighthearted"?"bg-violet-500 border-violet-400":"bg-slate-200 border-slate-300"}`,children:e.jsx("span",{className:`absolute left-0.5 top-0.5 h-4 w-4 rounded-full bg-white shadow-md transition-transform ${$e==="lighthearted"?"translate-x-5":"translate-x-0"}`})})})]}),(()=>{const t=!!(L!=null&&L.voiceUsedToday),a=t||dt,r=t?s.voiceUsedTodayLabel||"今日已使用":dt?s.voiceDisabledInIntensiveHint||(m==="zh"?"精读模式下将自动关闭语音模式":"Voice mode is disabled in intensive reading"):s.voiceModeSub,u=t?s.voiceUsedTodayLabel||"今日已使用":dt?s.voiceDisabledInIntensiveHint||(m==="zh"?"精读模式下将自动关闭语音模式":"Voice mode is disabled in intensive reading"):s.voiceModeHint;return e.jsxs("div",{className:`flex items-center rounded-xl border overflow-hidden ${c?"h-10 gap-2 px-2 py-1":"gap-3 px-4 py-2.5"} bg-pink-50/80 border-pink-100`,children:[e.jsxs("div",{className:`flex flex-col min-w-0 ${c?"max-w-[108px]":""}`,children:[e.jsx("span",{className:"truncate whitespace-nowrap text-[10px] font-black uppercase tracking-widest leading-none text-pink-600",children:s.voiceMode}),e.jsx("span",{className:"truncate whitespace-nowrap text-[8px] text-slate-500 font-bold opacity-80 leading-tight",children:r})]}),e.jsx("button",{type:"button",disabled:a,"aria-pressed":Y&&!a,"aria-label":u,title:u,onClick:()=>!a&&pe(l=>!l),className:`group relative h-11 w-11 shrink-0 focus-visible:outline-none ${c?"max-h-8 max-w-10":""} ${a?"cursor-not-allowed opacity-70":""}`,children:e.jsx("span",{className:`absolute inset-x-0 top-1/2 h-6 -translate-y-1/2 rounded-full border-2 transition-all duration-300 group-focus-visible:ring-2 group-focus-visible:ring-pink-300 group-focus-visible:ring-offset-2 ${a?"border-slate-300 bg-slate-200":Y?"border-pink-400 bg-pink-500":"border-slate-300 bg-slate-200"}`,children:e.jsx("span",{className:`absolute left-0.5 top-0.5 h-4 w-4 rounded-full bg-white shadow-md transition-transform duration-300 ${Y&&!a?"translate-x-5":"translate-x-0"}`})})})]})})(),Ke==="document"&&e.jsxs("div",{className:`flex items-center gap-3 rounded-xl border border-amber-100 bg-amber-50/80 overflow-hidden ${c?"h-10 px-2 py-1":"px-4 py-2.5"}`,children:[e.jsxs("div",{className:"flex min-w-0 flex-col",children:[e.jsx("span",{className:"text-[10px] font-black text-amber-700",children:m==="zh"?"图片解析":m==="ja"?"画像解析":m==="ru"?"Анализ изображений":"Image parsing"}),e.jsx("span",{className:"truncate text-[8px] font-bold text-slate-500",children:m==="zh"?"生成前识别文档配图":m==="ja"?"生成前に文書の画像を解析":m==="ru"?"Анализ изображений документа":"Analyze document images before generation"})]}),e.jsx("button",{type:"button",role:"switch","aria-checked":Pt,"aria-label":m==="zh"?"图片解析":"Image parsing","data-testid":"topic-image-parsing-toggle",onClick:()=>Bo(t=>!t),className:`relative h-6 w-11 shrink-0 rounded-full border-2 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-300 ${Pt?"border-amber-400 bg-amber-500":"border-slate-300 bg-slate-200"}`,children:e.jsx("span",{className:`absolute left-0.5 top-0.5 h-4 w-4 roun
136ded-full bg-white shadow-sm transition-transform ${Pt?"translate-x-5":""}`})})]}),Do]})]}),D!=="study_room"&&e.jsxs("div",{"data-testid":"topic-source-grid","data-start-mode-content":D,className:"steam-start-sources",children:[e.jsxs("div",{className:"steam-start-import",children:[e.jsxs("div",{className:"steam-start-import-header",children:[e.jsx("h3",{className:"steam-section-title",children:E.imports}),D==="story"?e.jsxs("div",{className:"steam-start-import-tabs",role:"tablist","aria-label":E.imports,children:[e.jsxs("button",{type:"button",role:"tab","aria-selected":Ke==="document","data-testid":"topic-import-document-tab",onClick:()=>{vt("document"),Be("")},children:[e.jsx(Ht,{size:15,"aria-hidden":"true"}),E.document]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":Ke==="video","data-testid":"topic-import-video-tab",onClick:()=>{vt("video"),kt([]),gt(null),ta(""),wt(!1)},children:[e.jsx(kn,{size:15,"aria-hidden":"true"}),E.video]})]}):e.jsxs("button",{type:"button",onClick:()=>{var t;return(t=ss.current)==null?void 0:t.click()},className:"steam-start-import-button",children:[e.jsx(Ht,{size:15,"aria-hidden":"true"}),E.importFile]})]}),(D!=="story"||Ke==="document")&&e.jsx(e.Fragment,{children:e.jsxs("div",{"data-testid":"topic-upload-dropzone",className:`relative group ${c?"h-20":"h-[clamp(112px,16cqh,166px)]"}`,children:[e.jsx("input",{ref:ss,id:"topic-upload-input",type:"file",accept:".txt,.md,.tex,.pdf,.docx,.pptx",multiple:Bt,onChange:Cr,className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10"}),e.jsx("div",{className:`h-full w-full rounded-2xl border-4 border-dashed transition-all duration-300 flex flex-col items-center justify-center text-center ${c?"p-2":"p-2 md:p-4"} overflow-hidden ${Ie?"border-otome-gold bg-yellow-50":"border-pink-200 bg-pink-50/50 group-hover:border-brand-pink group-hover:bg-pink-100"}`,children:Ie?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:`${c?"w-6 h-6":"w-6 h-6 md:w-12 md:h-12"} text-otome-gold mb-1 shrink-0`}),e.jsx("span",{className:`font-bold text-slate-700 ${c?"text-[10px]":"text-[10px] md:text-base"} w-full px-2 line-clamp-2 break-all leading-tight`,title:Ie,children:Ie})]}):e.jsxs(e.Fragment,{children:[e.jsx(wn,{className:"w-5 h-5 text-brand-pink mb-1 md:mb-2 shrink-0"}),e.jsx("p",{className:`font-bold text-slate-600 ${c?"text-xs":"text-xs md:text-base"}`,children:s.uploadPlaceholder}),e.jsx("p",{className:`text-slate-400 mt-0.5 ${c?"text-[10px]":"text-[8px] md:text-xs"}`,children:Qo})]})})]})}),D==="story"&&Ke==="video"&&e.jsxs("div",{"data-testid":"topic-video-field",className:"steam-start-video-field",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-wider block mb-1.5",children:m==="zh"?"视频链接":m==="ja"?"動画リンク":m==="ru"?"Ссылка на видео":"Video URL"}),e.jsxs("div",{className:"relative flex items-center",children:[e.jsx(Yt,{className:"absolute left-3 w-4 h-4 text-slate-400 pointer-events-none"}),e.jsx("input",{type:"url",value:Ft,onChange:t=>Be(t.target.value),placeholder:"Bilibili / YouTube / MP4",className:"w-full min-h-11 bg-slate-50 border border-slate-200 rounded-xl pl-9 pr-9 py-2 text-xs md:text-sm outline-none focus:border-brand-pink transition-colors",maxLength:2048}),Ft&&e.jsx("button",{type:"button",onClick:()=>Be(""),className:"absolute right-2 p-1 text-slate-400 hover:text-slate-700",title:m==="zh"?"清空视频链接":"Clear video URL",children:e.jsx(J,{className:"w-4 h-4"})})]})]})]}),D==="story"&&e.jsxs("details",{"data-testid":"topic-extra-entry",className:"steam-start-extra",children:[e.jsx("summary",{children:E.moreSources}),e.jsxs("div",{className:"steam-start-extra-content",children:[e.jsxs("div",{"data-testid":"topic-uuid-field",className:"min-w-0",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-wider block mb-2",children:s.orPlayByUuid}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"text",value:it,onChange:t=>es(t.target.value),placeholder:s.playByUuidPlaceholder,className:"flex-1 min-h-11 bg-slate-50 border border-slate-200 rounded-xl px-3 text-sm outline-none focus:border-brand-pink"}),e.jsx("button",{onClick:Wr,disabled:va||!it,className:`min-h-11 min-w-11 rounded-xl flex items-center justify-center ${va||!it?"bg-slate-100 text-slate-300":"bg-pink-100 text-pink-600 hover:bg-pink-500 hover:text-white"}`,children:va?e.jsx(He,{className:"w-5 h-5 animate-spin"}):e.jsx(So,{className:"w-5 h-5",fill:"currentColor"})})]})]}),e.jsxs("div",{"data-testid":"topic-preset-panel",className:"min-w-0",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-wider block mb-2",children:s.presetPapersTitle}),e.jsx("div",{className:"flex flex-col gap-2",children:(to[m]||to.en).map(t=>e.jsx("button",{onClick:()=>{n(t.script,"RUKA",!0),ae(!1)},className:"min-h-11 rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-left hover:border-pink-300",children:e.jsx("span",{className:"font-bold text-slate-700",children:t.title})},t.id))})]})]})]})]})]})]}),e.jsx("footer",{className:"steam-start-footer",children:e.jsx("button",{"data-testid":"start-mode-submit",onClick:Vr,disabled:D==="story"&&(b||Te),className:`${c?"order-4 h-14 roun
136ded-xl text-base gap-2.5":"h-20 md:h-20 rounded-xl md:rounded-2xl text-sm md:text-xl gap-2 md:gap-3"} font-black tracking-wide uppercase italic flex items-center justify-center shadow-xl border-[1px] border-white/40 transition-all duration-300 ${D==="story"&&(b||Te)?"bg-slate-100 text-slate-300 cursor-not-allowed":"bg-gradient-to-r from-rose-400 to-pink-600 text-white hover:brightness-110 shadow-rose-200"}`,children:D==="story"&&(b||Te)?e.jsx(He,{className:`${c?"w-5 h-5":"w-5 h-5 md:w-6 md:h-6"} animate-spin`}):e.jsx("span",{children:D==="study_room"?Ae.enterStudyRoom:D==="paper_qa"?Ae.startResearch:s.startExplain})})})]}),Eo&&e.jsx("div",{className:`${Le} z-[70]`,style:je,onClick:()=>!ze&&_e(!1),children:e.jsx("div",{className:`min-h-full w-full flex items-center justify-center ${c?"py-2":"py-4"}`,children:e.jsxs("div",{"data-testid":"steam-wishlist-modal-panel",className:`${ut} relative overflow-hidden flex flex-col min-h-0 ${c?"w-full max-w-md rounded-[18px] border-[2px] ring-1":"max-w-xl max-h-[90dvh] rounded-[28px] border-[4px] ring-2"}`,style:Nr,onClick:t=>t.stopPropagation(),children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 bg-gradient-to-br from-[#0b1220] via-[#1b2838] to-[#2a475e]"}),e.jsxs("div",{"data-testid":"steam-wishlist-modal-scroll",className:`relative flex-1 min-h-0 overflow-y-auto overscroll-y-contain custom-scrollbar text-white ${c?"p-3.5":"p-6"}`,style:he,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5 sm:gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:`${c?"w-10 h-10 rounded-xl":"w-12 h-12 rounded-2xl"} bg-white/12 text-white flex items-center justify-center shadow-lg shrink-0`,children:e.jsx("img",{src:ro,alt:"Steam",className:`${c?"w-5 h-5":"w-6 h-6"} object-contain`})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:`${c?"text-base sm:text-lg":"text-2xl"} font-black leading-tight`,children:s.steamWishlistTitle||"Paper2Gal 已上架 Steam"}),e.jsx("p",{className:`${c?"text-[10px]":"text-[11px]"} font-black uppercase tracking-[0.18em] sm:tracking-[0.2em] text-sky-200/90`,children:"Wishlist Bonu
136s +10"})]})]}),e.jsx("button",{type:"button",onClick:()=>_e(!1),disabled:ze,className:"p-2 rounded-full bg-white/12 text-slate-200 hover:text-white hover:bg-white/20 transition-colors disabled:opacity-50 shrink-0",children:e.jsx(J,{size:18,strokeWidth:3})})]}),e.jsxs("div",{className:`${c?"mt-3 p-3":"mt-4 p-4"} rounded-2xl border border-white/15 bg-white/8`,children:[e.jsx("div",{className:`${c?"text-[10px]":"text-[11px]"} uppercase font-black tracking-[0.14em] sm:tracking-[0.16em] text-sky-100/90`,children:"Steam Store"}),e.jsx("div",{className:`mt-1 ${c?"text-xs":"text-sm"} font-black text-white break-words`,children:Ua.replace("https://","")})]}),e.jsxs("div",{className:`${c?"mt-3 space-y-2.5":"mt-4 space-y-3"}`,children:[e.jsx("p",{className:`${c?"text-[13px]":"text-base"} text-slate-100/95 leading-relaxed font-medium`,children:s.steamWishlistDesc||"如果你愿意支持 Paper2Gal,欢迎将游戏加入 Steam 愿望单。这会帮助更多玩家看到游戏。"}),e.jsx("div",{className:`rounded-2xl border border-sky-200/25 bg-sky-4
13600/10 ${c?"px-3 py-2.5":"px-4 py-3"}`,children:e.jsx("p",{className:`${c?"text-[13px]":"text-sm"} font-bold text-sky-100 leading-relaxed`,children:s.steamWishlistRewardHint||"点击确定后将跳转到 Steam 商店页,并为当前账号发放 10 次永久使用次数。每个用户仅可领取一次。"})}),!f&&e.jsx("div",{className:`rounded-2xl border border-amber-200/30 bg-amber-300/10 ${c?"px-3 py-2.5 text-[13px]":"px-4 py-3 text-sm"} font-bold text-amber-100`,children:s.steamWishlistLoginHint||"请先登录后领取 Steam 愿望单奖励。"}),(L==null?void 0:L.steamWishlistRewardClaimed)&&e.jsx("div",{className:`rounded-2xl border border-emerald-200/30 bg-emerald-300/10 ${c?"px-3 py-2.5 text-[13px]":"px-4 py-3 text-sm"} font-bold text-emerald-100`,children:s.steamWishlistRewardClaimed||"Steam 愿望单奖励已领取过"})]}),e.jsxs("div",{className:`mt-5 flex ${c?"flex-col-reverse gap-2.5":"flex-row items-center justify-end gap-3"}`,children:[e.jsx("button",{type:"button",onClick:()=>_e(!1),disabled:ze,className:`${c?"w-full py-3":"px-4 py-2.5"} rounded-xl bg-white/12 text-slate-100 font-black hover:bg-white/20 transition-colors disabled:opacity-50`,children:s.steamWishlistCancel||"稍后再说"}),e.jsxs("button",{type:"button",onClick:Sr,disabled:ze,className:`${c?"w-full py-3 justify-center":"px-5 py-2.5"} rounded-xl bg-[#66c0f4] hover:bg-[#89d4ff] text-[#10233a] font-black shadow-lg transition-colors disabled:opacity-50 flex items-center gap-2`,children:[ze?e.jsx(He,{size:16,className:"animate-spin"}):e.jsx(eo,{size:16}),s.steamWishlistConfirm||"确定并前往 Steam"]})]})]})]})})}),$o&&e.jsx("div",{"data-testid":"community-backdrop",className:`${Le} z-[60]`,style:je,onClick:()=>Xe(!1),children:e.jsxs("section",{"data-testid":"community-panel",role:"dialog","aria-modal":"true","aria-labelledby":"community-title",className:"steam-community-panel",onClick:t=>t.stopPropagation(),children:[e.jsxs("header",{className:"steam-community-header",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h2",{id:"community-title",className:"font-black text-slate-800 tracking-tighter flex items-center gap-2",children:[e.jsx(Oa,{className:"text-brand-pink shrink-0"}),s.about]}),e.jsx("p",{className:"text-xs text-slate-400 font-bold",children:s.aboutSub})]}),e.jsx("button",{type:"button","data-testid":"community-close","aria-label":E.close,onClick:()=>Xe(!1),className:"steam-surface-close",children:e.jsx(J,{size:22})})]}),e.jsxs("div",{className:"steam-community-scroll custom-scrollbar",style:he,children:[e.jsxs("div",{"data-community-layout":"primary-grid",className:"steam-community-primary",children:[e.jsxs("a",{href:si,target:"_blank",rel:"noopener noreferrer",className:"steam-community-card bg-[#5865F2]",children:[e.jsx("img",{src:"/assets/local/common/discord-emblem.png",alt:"",className:"steam-discord-icon"}),e.jsxs("div",{children:[e.jsx("h3",{children:"Discord"}),e.jsx("p",{children:s.discordDesc})]})]}),e.jsxs("a",{href:"https://space.bilibili.com/472900263",target:"_blank",rel:"noopener noreferrer",className:"steam-community-card bg-[#FB7299]",children:[e.jsx("span",{className:"steam-community-icon",children:e.jsx("img",{src:"/assets/local/community/bilibili.svg",alt:""})}),e.jsxs("div",{children:[e.jsx("h3",{children:"Bilibili"}),e.jsx("p",{children:s.bilibiliDesc})]})]}),e.jsxs("button",{type:"button","data-testid":"wechat-preview-open","aria-label":E.previewQr,onClick:()=>oa(!0),className:"steam-community-card bg-[#07C160]",children:[e.jsx("span",{className:"steam-community-icon",children:e.jsx("img",{src:"/assets/local/community/wechat.svg",alt:""})}),e.jsxs("div",{children:[e.jsx("h3",{children:E.wechat}),e.jsx("p",{children:s.wechatDesc})]})]})]}),e.jsxs("div",{"data-community-layout":"secondary-bars",className:"steam-community-secondary",children:[e.jsxs("a",{href:oi,target:"_blank",rel:"noopener noreferrer",className:"steam-community-bar bg-[#ff2442]",children:[e.jsx("img",{src:"/assets/local/community/xiaohongshu.svg",alt:""}),e.jsxs("div",{children:[e.jsx("h3",{children:E.xiaohongshu}),e.jsx("p",{children:E.follow})]})]}),e.jsxs("a",{href:ri,target:"_blank",rel:"noopener noreferrer",className:"steam-community-bar bg-[#161823] border-[#25f4ee] hover:border-[#fe2c55]",children:[e.jsx("img",{src:"/assets/local/community/douyin.svg",alt:"",className:"[filter:drop-shadow(-1px_-1px_0_#25f4ee)_drop-shadow(1px_1px_0_#fe2c55)]"}),e.jsxs("div",{children:[e.jsx("h3",{children:E.douyin}),e.jsx("p",{children:E.follow})]})]}),e.jsxs("div",{className:"steam-community-bar bg-[#12b7f5]",children:[e.jsx("img",{src:"/assets/local/community/qq.svg",alt:""}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{children:E.qqGroup}),e.jsx("span",{"data-testid":"qq-number",className:"select-text cursor-text",children:no})]}),e.jsx("button",{type:"button","data-testid":"qq-copy",className:"min-h-11 rounded-xl bg-white/20 px-3 text-xs font-bold",onClick:async()=>{try{await navigator.clipboard.writeText(no)}catch{await A(E.copyFailed,{variant:"error"});return}await A(E.copied,{variant:"success"})},children:E.copyQq})]})]}),e.jsxs("div",{className:"mt-4 md:mt-6 flex flex-wrap justify-center items-center gap-4 md:gap-8 opacity-60 hover:opacity-100 transition-opacity",children:[e.jsxs("button",{"data-testid":"community-terms",onClick:()=>ue(m==="zh"?"/docs/Terms_Of_Service_CN.md":"/docs/Terms_Of_Service_EN.md",s.termsOfService||"Terms of Service"),className:"text-xs md:text-sm font-bold text-slate-500 hover:text-pink-500 transition-colors flex items-center gap-1 cursor-pointer",children:[e.jsx(Ht,{size:12,className:"md:w-4 md:h-4"}),s.termsOfService||"Terms of Service"]}),e.jsxs("button",{"data-testid":"community-privacy",onClick:()=>ue(m==="zh"?"/docs/Privacy_Policy_CN.md":"/docs/Privacy_Policy_EN.md",s.privacyPolicy||"Privacy Policy"),className:"text-xs md:text-sm font-bold text-slate-500 hover:text-pink-500 transition-colors flex items-center gap-1 cursor-pointer",children:[e.jsx(vn,{size:12,className:"md:w-4 md:h-4"}),s.privacyPolicy||"Privacy Policy"]})]})]})]})}),To&&e.jsx("div",{"data-testid":"wechat-preview",className:`${Le} z-[70] bg-black/70`,style:je,onClick:()=>oa(!1),children:e.jsxs("div",{className:"steam-wechat-preview",onClick:t=>t.stopPropagation(),children:[e.jsx("button",{type:"button",onClick:()=>oa(!1),className:"absolute top-2 right-2 md:top-3 md:right-3 h-11 w-11 flex items-center justify-center rounded-full bg-black/10 hover:bg-red-50 hover:text-red-500 text-slate-500 transition-colors z-10","data-testid":"wechat-preview-close","aria-label":E.closeQr,children:e.jsx(J,{size:18,className:"md:w-5 md:h-5",strokeWidth:3})}),e.jsx("img",{src:Jn,"data-testid":"wechat-preview-image",alt:E.qrAlt,className:"steam-wechat-image"})]})}),zo&&e.jsx("div",{className:`${Le} z-[70]`,style:je,onClick:()=>_t(!1),children:e.jsxs("div",{className:`${ut} flex flex-col items-center text-center relative overflow-hidden ${c?"max-w-[320px] rounded-[18px] p-4 border-[2px] ring-1 max-h-[90dvh] overflow-y-auto custom-scrollbar overscroll-y-contain":"max-w-sm rounded-[24px] p-6 border-[4px] ring-2"}`,style:he,onClick:t=>t.stopPropagation(),children:[e.jsx("div",{className:"absolute top-0 left-0 w-full h-2 bg-gradient-to-r from-pink-300 via-rose-400 to-pink-300"}),e.jsx("div",{className:"mb-4 p-3 md:p-4 bg-pink-50 rounded-full text-pink-500 shadow-inner transform rotate-6 ring-4 ring-pink-50/50",children:e.jsx(Ca,{size:32,strokeWidth:2.5})}),e.jsx("h3",{className:`${c?"text-lg":"text-xl"} font-black text-slate-800 mb-2 tracking-tight`,children:s.loginRequired}),e.jsx("p",{className:`${c?"text-xs mb-6":"text-sm mb-8"} text-slate-500 font-bold leading-relaxed`,children:s.loginRequiredMsg}),e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>_t(!1),className:"flex-1 py-3 bg-slate-100 text-slate-400 rounded-2xl font-black text-sm hover:bg-slate-200 hover:text-slate-600 transition-colors",children:s.cancel}),e.jsxs("button",{onClick:()=>{_t(!1),j()},className:"flex-1 py-3 bg-gradient-to-r from-pink-500 to-rose-600 text-white rounded-2xl font-black text-sm shadow-lg shadow-pink-200 hover:shadow-xl hover:shadow-
136pink-300 hover:-translate-y-0.5 transition-all flex items-center justify-center gap-2",children:[e.jsx(Ca,{size:16})," ",s.login]})]})]})}),aa&&!Da&&!Ka&&e.jsx("div",{className:`${Le} z-50`,style:je,onClick:()=>ne(!1),children:e.jsxs("div",{className:`${ut} p-2 flex flex-col relative overflow-hidden ${c?"mobile-landscape-modal rounded-[18px] min-h-0 border-[2px] ring-1":"w-[60%] md:w-full max-w-5xl rounded-[24px] md:rounded-[32px] md:p-8 border-[4px] md:border-[6px] ring-2 max-h-[90dvh]"}`,onClick:t=>t.stopPropagation(),children:[e.jsxs("div",{className:"flex justify-between items-center gap-2 mb-2 shrink-0 border-b border-slate-100 pb-2 pl-2 bg-[#fffdfd]",children:[e.jsxs("h2",{className:`${c?"text-lg":"text-lg md:text-3xl"} font-black text-slate-800 tracking-tighter flex items-center gap-2 md:gap-3`,children:[e.jsx(Oa,{className:"text-brand-pink"}),s.selectPartner]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:e.jsx("button",{onClick:()=>ne(!1),className:"p-2 bg-white hover:bg-red-50 text-slate-400 hover:text-red-500 rounded-full shadow transition-all",children:e.jsx(J,{size:24})})})]}),e.jsxs("div",{className:`${c?"grid grid-cols-4 gap-1.5":"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-2 md:gap-3"} overflow-y-auto custom-scrollbar overscroll-y-contain p-1 md:p-2 flex-1 min-h-0`,style:he,children:[B.map(t=>{var i;const a=Zr(t),r=a.length>1,u=Co===t.id,l=La(t,g===t.id?x:void 0);if(u&&r){const p=x||((i=a[0])==null?void 0:i.id);return e.jsx("div",{className:"col-span-full",children:e.jsx("div",{className:`rounded-3xl border border-pink-200 bg-gradient-to-br from-pink-50 via-rose-50 to-orange-50 shadow-sm animate-[fadeIn_.18s_ease-out] ${c?"p-2":"p-3 md:p-4"}`,children:e.jsxs("div",{className:`rounded-[22px] border border-white/80 bg-white/60 ${c?"p-1.5 flex items-start gap-1.5 overflow-x-auto custom-scrollbar":"p-2 md:p-3 flex items-start gap-2 md:gap-3 overflow-x-auto custom-scrollbar"}`,children:[e.jsx("div",{className:`${c?"shrink-0 w-[calc((100%-4.5px)/4)] aspect-[3/4]":"shrink-0 w-[180px] h-[280px]"}`,children:e.jsx(qt,{id:t.id,name:qe(t),imgSrc:(l==null?void 0:l.coverUrl)||t.avatarUrl,colorClass:t.colorClass,isSelected:g===t.id,hasChildren:r,isExpanded:!0,onSelect:()=>{k(t.id),sa(M=>M===t.id?null:t.id)},onAdjustLayout:(M,_)=>Wt(t.id,(l==null?void 0:l.id)||null,_),t:s})}),a.map(M=>{const _=p===M.id;return e.jsx("div",{className:`${c?"shrink-0 w-[calc((100%-4.5px)/4)] aspect-[3/4]":"shrink-0 w-[180px] h-[280px]"}`,children:e.jsx(qt,{id:`${t.id}:${M.id}`,name:M.name,imgSrc:M.coverUrl,colorClass:t.colorClass,isSelected:_,isSubCard:!0,onSelect:()=>{k(t.id),w(t.id,M.id),ne(!1)},onAdjustLayout:(C,T)=>Wt(t.id,M.id,T),t:s})},`${t.id}-skin-${M.id}`)})]})})},t.id)}return e.jsx("div",{className:`w-full ${c?"aspect-[3/4]":"h-[150px] md:h-[280px]"}`,children:e.jsx(qt,{id:t.id,name:qe(t),imgSrc:(l==null?void 0:l.coverUrl)||t.avatarUrl,colorClass:t.colorClass,isSelected:g===t.id,hasChildren:r,isExpanded:u,onSelect:()=>{if(k(t.id),!r){ne(!1);return}sa(p=>p===t.id?null:t.id)},onAdjustLayout:(p,M)=>Wt(t.id,(l==null?void 0:l.id)||null,M),t:s})},t.id)}),y.map(t=>e.jsx("div",{className:`w-full ${c?"aspect-[3/4]":"h-[150px] md:h-[280px]"}`,children:e.jsx(qt,{id:t.id,name:t.name,imgSrc:t.avatarUrl,colorClass:"from-purple-100 via-blue-100 to-transparent",isCustom:!0,isSelected:g===t.id,onSelect:()=>{k(t.id),ne(!1)},onDelete:zr,onEdit:Br,onAdjustLayout:(a,r)=>Wt(t.id,null,r),isShared:t.isShared,isBorrowed:t.isBorrowed,borrowCount:t.borrowCount,hasVoice:!!t.voiceRefAudioUrl,t:s})},t.id)),e.jsx("div",{className:`w-full ${c?"aspect-[3/4]":"h-[200px] md:h-[280px]"}`,children:e.jsxs("div",{onClick:()=>Fe(!0),className:"relative group cursor-pointer rounded-2xl border-[3px] border-dashed border-slate-300 hover:border-blue-400 bg-slate-50 hover:bg-blue-50 transition-all duration-300 flex flex-col items-center justify-center h-full gap-3 overflow-hidden",children:[e.jsx("div",{className:"p-4 bg-white rounded-full shadow-sm group-hover:shadow-md transition-all",children:e.jsx(Yt,{size:32,className:"text-slate-400 group-hover:text-blue-500"})}),e.jsx("span",{className:"font-bold text-slate-500 group-hover:text-blue-500 uppercase text-sm",children:s.borrowTitle})]})}),e.jsx("div",{className:`w-full ${c?"aspect-[3/4]":"h-[200px] md:h-[280px]"}`,children:e.jsxs("div",{onClick:async()=>
136{if(!f){await A(s.loginRequired,{variant:"info"}),j();return}Ra(),yt(!0)},className:"relative cursor-pointer group rounded-2xl border-[3px] border-dashed border-slate-300 hover:border-brand-pink bg-slate-50 hover:bg-pink-50 transition-all duration-300 flex flex-col items-center justify-center h-full gap-3",children:[e.jsx("div",{className:"p-4 bg-white rounded-full shadow-sm group-hover:shadow-md transition-all",children:e.jsx(ht,{size:32,className:"text-slate-400 group-hover:text-brand-pink"})}),e.jsx("span",{className:"font-bold text-slate-500 group-hover:text-brand-darkPink",children:s.createCustomBtn})]})})]})]})}),e.jsx(so,{isOpen:Mo,onClose:()=>za(!1),characterId:g,skinId:de?x:null,characterName:ys,spriteUrl:We,live2dConfig:Vt,defaultLayout:ce==null?void 0:ce.layout,language:m,uiPreset:v}),e.jsx(so,{isOpen:se!==null,onClose:()=>Ct(null),onSave:t=>{Ct(null),Ms(t)},characterId:(se==null?void 0:se.id)||"",characterName:(se==null?void 0:se.name)||"",spriteUrl:(se==null?void 0:se.spriteUrl)||"",language:m,uiPreset:v}),Ka&&e.jsx("div",{className:`${Le} z-[65]`,style:je,onClick:()=>Fe(!1),children:e.jsxs("div",{className:`${ut} flex flex-col items-center text-center relative overflow-hidden ${c?"mobile-landscape-modal min-h-0 p-4 rounded-[18px] border-[2px] ring-1 overflow-y-auto custom-scrollbar overscroll-y-contain":"max-w-sm p-6 rounded-[24px] border-[4px] ring-2"}`,style:he,onClick:t=>t.stopPropagation(),children:[e.jsx("button",{onClick:()=>Fe(!1),className:"absolute top-4 right-4 p-2 bg-slate-50 hover:bg-red-50 text-slate-400 hover:text-red-500 rounded-full transition-all",children:e.jsx(J,{size:20,strokeWidth:3})}),e.jsx("div",{className:"mb-4 p-3 md:p-4 bg-purple-50 rounded-full text-purple-500 shadow-inner transform rotate-6 ring-4 ring-purple-50/50",children:e.jsx(Yt,{size:32,strokeWidth:2.5})}),e.jsx("h3",{className:`${c?"text-lg":"text-xl"} font-black text-slate-800 mb-2 tracking-tight`,children:s.borrowTitle}),e.jsx("p",{className:`${c?"text-xs":"text-sm"} text-slate-500 font-bold mb-6 leading-relaxed`,children:s.borrowDesc}),e.jsxs("button",{type:"button",onClick:()=>{Fe(!1),ne(!1),P()},className:"group mb-5 flex w-full items-center gap-3 rounded-2xl border border-pink-200 bg-gradient-to-r from-pink-50 to-violet-50 p-3 text-left shadow-sm transition-all hover:border-pink-300 hover:shadow-md active:scale-[0.99]","aria-label":m==="zh"?"去创意工坊挑选角色":`${s.communityTitle||"Workshop"} characters`,children:[e.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-white text-pink-500 shadow-sm transition-transform group-hover:scale-105",children:e.jsx(Oa,{size:20})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block text-sm font-black text-slate-700",children:m==="zh"?"去创意工坊挑选角色":m==="ja"?"ワークショップでキャラを探す":m==="ru"?"Выбрать персонажа в Мастерской":"Browse Workshop Characters"}),e.jsx("span",{className:"block truncate text-[10px] font-bold text-slate-400",children:m==="zh"?"浏览社区公开角色并一键借阅":m==="ja"?"公開キャラを閲覧して借用":m==="ru"?"Просмотр и заимствование общих персонажей":"Browse and borrow public characters"})]})]}),e.jsxs("div",{className:"mb-4 flex w-full items-center gap-3 text-[10px] font-black uppercase tracking-widest text-slate-300",children:[e.jsx("span",{className:"h-px flex-1 bg-slate-200"}),e.jsx("span",{children:m==="zh"?"或使用角色 UUID":"Or use character UUID"}),e.jsx("span",{className:"h-px flex-1 bg-slate-200"})]}),e.jsx("input",{type:"text",value:Et,onChange:t=>Xa(t.target.value),placeholder:s.uuidPlaceholder,className:"w-full p-3 bg-slate-50 border border-slate-200 rounded-xl focus:border-purple-500 outline-none text-sm mb-6"}),e.jsxs("button",{onClick:Ir,disabled:It||!Et,className:`w-full py-3 rounded-2xl font-black text-sm shadow-lg transition-all flex items-center justify-center gap-2 ${It?"bg-slate-300 text-white cursor-wait":"bg-gradient-to-r from-purple-500 to-pink-600 text-white hover:brightness-110 shadow-purple-200"}`,children:[It?e.jsx(He,{size:16,className:"animate-spin"}):e.jsx(Yt,{size:16}),It?s.borrowing:s.borrowBtn]})]})}),Da&&e.jsx("div",{className:`${Le} z-[60]`,style:je,children:e.jsxs("div",{className:`${ut} flex flex-col relative overflow-y-auto custom-scrollbar overscroll-y-contain ${c?"mobile-landscape-modal min-h-0 rounded-[18px] p-3 border-[2px] ring-1":"w-[90%] md:w-full max-w-2xl rounded-[16px] md:rounded-[24px] p-3 md:p-8 border-[4px] md:border-[6px] ring-2 max-h-[90dvh]"}`,style:he,onClick:t=>t.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 md:mb-6 shrink-0",children:[e.jsxs("h3",{className:`${c?"text-lg":"text-lg md:text-2xl"} font-black text-slate-800 flex items-center gap-2`,children:[e.jsx(Pa,{className:"text-brand-pink"}
136)," ",V?s.editCharTitle:s.createCharTitle]}),e.jsx("button",{onClick:Cs,className:"p-2 bg-slate-50 hover:bg-red-50 text-slate-400 hover:text-red-500 rounded-full transition-all",children:e.jsx(J,{size:18,strokeWidth:3})})]}),e.jsxs("div",{className:c?"space-y-3":"space-y-2 md:space-y-4",children:[e.jsxs("div",{className:c?"grid grid-cols-1 gap-2":"grid grid-cols-1 md:grid-cols-2 gap-2 md:gap-4",children:[e.jsxs("div",{className:"space-y-0.5 md:space-y-2",children:[e.jsx("label",{className:"text-[10px] md:text-xs font-bold text-slate-500 uppercase",children:s.charIdLabel}),e.jsxs("div",{className:`flex items-center bg-slate-50 border border-slate-200 focus-within:border-brand-pink outline-none font-mono ${c?"p-2 rounded-lg text-xs":"p-2 md:p-3 rounded-lg md:rounded-xl text-xs md:text-base"}`,children:[e.jsx("span",{className:"text-gray-400",children:"u_"}),e.jsx("input",{type:"text",value:Je,onChange:t=>ra(t.target.value.toUpperCase().replace(/[^A-Z0-9_]/g,"")),placeholder:s.charIdPlaceholder,className:`flex-1 outline-none text-slate-700 bg-transparent placeholder-slate-300 ${V?"opacity-60 cursor-not-allowed":""}`,disabled:!!V})]}),e.jsx("p",{className:"text-[10px] text-slate-400 mt-1",children:s.idHint})]}),e.jsxs("div",{className:"space-y-0.5 md:space-y-2",children:[e.jsx("label",{className:"text-[10px] md:text-xs font-bold text-slate-500 uppercase",children:s.charNameLabel}),e.jsx("input",{type:"text",value:Ze,onChange:t=>na(t.target.value),placeholder:s.charNamePlaceholder,className:`w-full bg-slate-50 border border-slate-200 focus:border-brand-pink outline-none ${c?"p-2 rounded-lg text-xs":"p-2 md:p-3 rounded-lg md:rounded-xl text-xs md:text-base"}`})]})]}),V&&e.jsxs("div",{className:"pt-2",children:[e.jsx("label",{className:"text-xs font-bold text-slate-400 uppercase tracking-wider mb-2 block",children:s.shareUuidLabel}),e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-slate-50 rounded-lg border border-slate-200",children:[e.jsx("code",{className:"text-[10px] text-slate-700 font-mono flex-1 overflow-x-auto",children:((qs=y.find(t=>t.id===V))==null?void 0:qs.dbId)||"N/A"}),e.jsx("button",{onClick:async()=>{var a;const t=(a=y.find(r=>r.id===V))==null?void 0:a.dbId;t&&(navigator.clipboard.writeText(t),await A(s.uuidCopied,{variant:"success"}))},className:"p-1 px-2 text-[10px] bg-white border border-slate-200 rounded hover:bg-slate-50 transition-colors",children:s.copyBtn})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 bg-blue-50 rounded-xl border border-blue-100",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yn,{size:18,className:"text-blue-500"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-bold text-blue-700",children:s.shareToggleTitle}),e.jsx("span",{className:"text-[10px] text-blue-500",children:s.shareToggleDesc})]})]}),e.jsx("button",{onClick:()=>da(!et),className:`w-12 h-6 rounded-full transition-all duration-300 relative ${et?"bg-blue-500":"bg-slate-300"}`,children:e.jsx("div",{className:`absolute top-1 w-4 h-4 bg-white rounded-full transition-all duration-300 ${et?"left-7":"left-1"}`})})]}),e.jsxs("div",{className:"space-y-0.5 md:space-y-2",children:[e.jsx("label",{className:"text-[10px] md:text-xs font-bold text-slate-500 uppercase",children:s.charImgLabel}),e.jsxs("div",{className:`relative w-full border-2 border-dashed border-slate-300 bg-slate-50 flex items-center justify-center overflow-hidden group hover:border-brand-pink transition-colors ${c?"h-20 rounded-lg":"h-20 md:h-32 rounded-lg md:rounded-xl"}`,children:[e.jsx("input",{type:"file",accept:"image/*",onChange:Or,className:"absolute inset-0 opacity-0 cursor-pointer z-10"}),Ne?e.jsx("img",{src:Ne,className:"h-full object-contain",alt:"Preview"}):e.jsxs("div",{className:"flex flex-col items-center text-slate-400",children:[e.jsx(Nn,{size:16,className:"md:w-6 md:h-6"}),e.jsx("span",{className:"text-[10px] md:text-xs mt-1",children:s.uploadClick})]})]})]}),e.jsxs("div",{className:"space-y-0.5 md:space-y-2 relative",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("label",{className:"text-[10px] md:text-xs font-bold text-slate-500 uppercase",children:s.charPromptLabel}),e.jsx("button",{type:"button",onClick:t=>{t.preventDefault(),t.stopPropagation(),lt(!as)},className:"p-0.5 text-slate-400 hover:text-brand-pink transition-colors rounded-full hover:bg-pink-50",title:s.charPromptHelpTitle,children:e.jsx(Sn,{size:14})})]}),as&&e.jsxs("div",{className:"absolute z-30 top-5 left-0 right-0 bg-white border border-pink-200 rounded-xl shadow-xl p-3 md:p-4 animate-fade-in",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("h4",{className:"text-xs md:text-sm font-black text-brand-darkPink flex items-center gap-1.5",children:[e.jsx(Pa,{size:14,className:"text-pink-400"}),s.charPromptHelpTitle]}),e.jsx("button",{onClick:()=>lt(!1),className:"p-1 hover:bg-slate-100 rounded-full text-slate-400 hover:text-slate-600 transition-colors",children:e.jsx(J,{size:14})})]}),e.jsx("div",{className:"bg-pink-50/60 border border-pink-100 rounded-lg p-2.5 md:p-3 max-h-48 md:max-h-64 overflow-y-auto custom-scrollbar",children:e.jsx("pre",{className:"text-[9px] md:text-[11px] text-slate-600 whitespace-pre-wrap font-sans leading-relaxed",children:s.charPromptHelpContent})}),e.jsx("p",{className:"text-[8px] md:text-[10px] text-slate-400 mt-2 italic",children:s.charPromptHelpHint})]}),e.jsx("textarea",{value:Nt,onChange:t=>{ia(t.target.value),ee(null)},placeholder:s.charPromptPlaceholder,className:`w-full bg-slate-50 border outline-none resize-none transition-all ${c?"h-20 p-2 rounded-lg text-xs":"h-20 md:h-32 p-2 md:p-3 rounded-lg md:rounded-xl text-xs md:text-sm"} ${ba?"border-red-400 bg-red-50 focus:border-red-500":"border-slate-200 focus:border-brand-pink"}`,onFocus:()=>lt(!1)}),e.jsx("p",{className:"text-[9px] leading-relaxed text-amber-600",children:s.charPromptBackgroun
136dHint}),ba&&e.jsxs("div",{className:"flex items-start gap-2 text-red-500 text-[10px] md:text-xs font-bold bg-red-50 p-2 md:p-3 rounded-lg border border-red-100 animate-shake",children:[e.jsx("div",{className:"mt-0.5 shrink-0",children:"⚠️"}),e.jsx("div",{className:"leading-tight",children:ba})]})]}),e.jsxs("div",{className:"space-y-2 p-3 bg-pink-50/50 rounded-xl border border-pink-100",children:[e.jsx("label",{className:"text-[10px] md:text-xs font-bold text-slate-500 uppercase block",children:s.charVoiceRefTextLabel||"参考语音文本 (可选)"}),e.jsx("textarea",{value:ma,onChange:t=>pa(t.target.value),placeholder:s.charVoiceRefTextPlaceholder||"What the reference audio says, for voice cloning",className:`w-full bg-white border border-slate-200 focus:border-brand-pink outline-none resize-none rounded-lg ${c?"h-14 p-2 text-xs":"h-14 md:h-16 p-2 md:p-3 text-xs md:text-sm"}`,rows:2}),e.jsx("label",{className:"text-[10px] md:text-xs font-bold text-slate-500 uppercase block mt-2",children:s.charVoiceRefAudioLabel||"参考语音音频 (可选)"}),e.jsx("p",{className:"text-[9px] text-slate-400 mb-1",children:s.charVoiceRefAudioHint||"建议 5–15 秒,最长 20 秒且不超过 500KB"}),e.jsxs("div",{className:`relative w-full border-2 border-dashed border-slate-300 bg-white flex items-center justify-center overflow-hidden group hover:border-brand-pink transition-colors rounded-lg ${c?"h-14":"h-14 md:h-16"}`,children:[e.jsx("input",{type:"file",accept:"audio/*,.wav,.mp3",onChange:t=>{var r;const a=((r=t.target.files)==null?void 0:r[0])||null;Ur(a)},className:"absolute inset-0 opacity-0 cursor-pointer z-10"}),F||W?e.jsx("span",{className:"text-xs font-bold text-slate-600 truncate px-2",children:(F==null?void 0:F.name)||(W==null?void 0:W.name)}):V&&((Hs=y.find(t=>t.id===V))!=null&&Hs.voiceRefAudioUrl)?e.jsxs("div",{className:"flex items-center gap-1.5 text-brand-pink font-bold text-[10px] md:text-xs px-2",children:[e.jsx(No,{size:14}),e.jsx("span",{children:s.charVoiceRefUploadedHint||"已上传参考语音 · 选择新文件可替换"})]}):e.jsx("span",{className:"text-[10px] md:text-xs text-slate-400",children:"WAV / MP3"})]}),F&&at&&e.jsxs("div",{className:"space-y-2 rounded-lg border border-pink-100 bg-white p-2",children:[e.jsx("audio",{ref:fa,controls:!0,src:at,onLoadedMetadata:_r,onTimeUpdate:t=>rt(t.currentTarget.currentTime),onSeeked:t=>rt(t.currentTarget.currentTime),className:"w-full h-9"}),e.jsx(ci,{peaks:Io,duration:Z,start:st,end:ot,currentTime:_o,loading:Uo,onRangeChange:(t,a)=>{Se(t),Re(a)},onSeek:t=>{fa.current&&(fa.current.currentTime=t),rt(t)}}),e.jsxs("div",{className:"flex flex-wrap items-end gap-2",children:[e.jsxs("label",{className:"flex-1 min-w-[92px]",children:[e.jsx("span",{className:"block text-[9px] font-bold text-slate-400 uppercase",children:s.charVoiceRefTrimStart||"开始"}),e.jsx("input",{type:"number",min:0,max:Z||void 0,step:"0.1",value:st,onChange:t=>Se(Number(t.target.value)),className:"mt-1 w-full rounded-md border border-slate-200 bg-slate-50 px-2 py-1 text-xs font-bold text-slate-600 outline-none focus:border-brand-pink"})]}),e.jsxs("label",{className:"flex-1 min-w-[92px]",children:[e.jsx("span",{className:"block text-[9px] font-bold text-slate-400 uppercase",children:s.charVoiceRefTrimEnd||"结束"}),e.jsx("input",{type:"number",min:0,max:Z||void 0,step:"0.1",value:ot,onChange:t=>Re(Number(t.target.value)),className:"mt-1 w-full rounded-md border border-slate-200 bg-slate-50 px-2 py-1 text-xs font-bold text-slate-600 outline-none focus:border-brand-pink"})]}),e.jsxs("button",{type:"button",onClick:Pr,disabled:Ga||!Z,className:"inline-flex h-8 items-center justify-center gap-1.5 rounded-md bg-brand-pink px-3 text-[10px] font-bold text-white shadow-sm transition-colors hover:bg-pink-500 disabled:cursor-not-allowed disabled:opacity-60",children:[Ga?e.jsx(He,{size:13,className:"animate-spin"}):e.jsx(Rn,{size:13}),e.jsx("span",{children:s.charVoiceRefTrimButton||"裁剪"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 text-[9px] text-slate-400",children:[e.jsx("span",{children:Z>0?`${s.charVoiceRefDuration||"时长"} ${Si(Z)}`:s.charVoiceRefLoadingDuration||"正在读取音频时长"}),W&&e.jsxs("span",{className:"font-bold text-emerald-600",children:[s.charVoiceRefTrimReady||"已准备上传"," · ",(W.size/1024).toFixed(0),"KB"]})]}),qa&&e.jsx("div",{className:"rounded-md border border-amber-100 bg-amber-50 px-2 py-1 text-[10px] font-bold text-amber-700",children:qa})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-[10px] md:text-xs font-bold text-slate-500 uppercase flex items-center gap-2",children:[s.expressionsLabel," ",e.jsx("span",{className:"text-[9px] bg-slate-100 px-1 rounded",children:s.maxSizeLabel})]}),e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2 custom-scrollbar",children:Ks.map(t=>e.jsxs("div",{className:`shrink-0 relative border border-dashed border-slate-300 rounded-lg bg-slate-50 flex flex-col items-center justify-center overflow-hidden group hover:border-brand-pink ${c?"w-20 h-24":"w-20 h-24 md:w-24 md:h-28"}`,children:[e.jsx("input",{type:"file",accept:"image/*",onChange:a=>$r(a,t),className:"absolute inset-0 opacity-0 cursor-pointer z-10"}),tt[t]?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:tt[t],className:"h-full w-full object-contain"}),e.jsx("button",{onClick:a=>{a.preventDefault(),a.stopPropagation(),Tr(t)},className:"absolute top-1 right-1 p-1 bg-white/80 rounded-full text-red-500 hover:bg-red-500 hover:text-white z-20",children:e.jsx(J,{size:10})}),e.jsx("span",{className:"absolute bottom-0 w-full bg-black/50 text-white text-[9px] text-center font-bold",children:t})]}):e.jsxs(e.Fragment,{children:[e.jsx(ht,{size:16,className:"text-slate-300 group-hover:text-brand-pink mb-1"}),e.jsx("span",{className:"text-[9px] text-slate-400 font-bold uppercase",children:t})]})]},t))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-[10px] md:text-xs font-bold text-slate-500 uppercase flex items-center gap-2",children:[s.endingCgLabel||"Ending CG"," ",e.jsx("span",{className:"text-[9px] bg-slate-100 px-1 rounded",children:s.endingCgLimitLabel||"Max 3 images / 5MB"})]}),e.jsxs("div",{className:"flex gap-2 overflow-x-auto pb-2 custom-scrollbar",children:[Rt.map((t,a)=>e.jsxs("div",{className:`shrink-0 relative border border-slate-200 rounded-lg bg-slate-50 flex items-center justify-center overflow-hidden ${c?"w-20 h-24":"w-20 h-24 md:w-24 md:h-28"}`,children:[e.jsx("input",{type:"file",accept:"image/*",onChange:r=>As(r,a),className:"absolute inset-0 opacity-0 cursor-pointer z-10"}),e.jsx("img",{src:t,className:"h-full w-full object-cover"}),e.jsx("button",{onClick:r=>{r.preventDefault(),r.stopPropagation(),Er(a)},className:"absolute top-1 right-1 p-1 bg-white/80 rounded-full text-red-500 hover:bg-red-500 hover:text-white z-20",children:e.jsx(J,{size:10})})]},`cg-${a}`)),Rt.length<3&&e.jsxs("label",{className:`shrink-0 relative border border-dashed border-slate-300 rounded-lg bg-slate-50 flex flex-col items-center justify-center overflow-hidden group hover:border-brand-pink cursor-pointer ${c?"w-20 h-24":"w-20 h-24 md:w-24 md:h-28"}`,children:[e.jsx("input",{type:"file",accept:"image/*",onChange:t=>As(t),className:"absolute inset-0 opacity-0 cursor-pointer z-10"}),e.jsx(ht,{size:16,className:"text-slate-300 group-hover:text-brand-pink mb-1"}),e.jsx("span",{className:"text-[9px] text-slate-400 font-bold uppercase",children:"CG"})]})]})]}),e.jsxs("div",{className:c?"flex gap-2 pt-2":"flex gap-2 md:gap-3 pt-2 md:pt-4",children:[e.jsx("button",{onClick:Cs,className:`${c?"py-2 rounded-lg text-xs":"py-2 md:py-3 rounded-lg md:rounded-xl text-xs md:text-base"} flex-1 bg-slate-100 text-slate-600 font-bold hover:bg-slate-200 transition-colors`,disabled:jt,children:s.cancel}),e.jsx("button",{onClick:()=>void Ms(),disabled:jt,className:`
137                                        flex-1 ${c?"py-2 rounded-lg text-xs":"py-2 md:py-3 rounded-lg md:rounded-xl text-xs md:text-base"} font-bold shadow-lg transition-all flex items-center justify-center gap-2
138                                        ${jt?"bg-slate-300 text-white cursor-wait relative overflow-hidden":"bg-gradient-to-r from-brand-pink to-brand-darkPink text-white hover:brightness-110"}
139                                    `,children:jt?e.jsxs(e.Fragment,{children:[e.jsx(He,{size:16,className:"animate-spin"}),e.jsx("span",{children:s.checking}),e.jsx("div",{className:"absolute bottom-0 left-0 h-1 bg-white/30 animate-progress-indeterminate w-full"})]}):e.jsx("span",{children:V?s.update:s.create})})]})]})]})})]})};export{Wi as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.