Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit6ce73cd

Browse files
josixbeccalzh
andcommitted
feat: add tui interactive interface to work with llm translation
Co-Authored-By: Becca <beccalin.8359@gmail.com>
1 parentc4c0d58 commit6ce73cd

File tree

3 files changed

+893
-112
lines changed

3 files changed

+893
-112
lines changed
Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
1+
importos
2+
importgoogle.generativeaiasgenai
3+
4+
fromtextual.appimportApp,ComposeResult
5+
fromtextual.widgetsimportHeader,Footer,Input,Button,Static
6+
fromtextual.containersimportContainer
7+
fromtextual.bindingimportBinding
8+
importpolib
9+
frompathlibimportPath
10+
importsubprocess
11+
12+
classTranslationApp(App):
13+
BINDINGS= [
14+
Binding("left","previous","Previous Entry"),
15+
Binding("right","next","Next Entry"),
16+
Binding("enter","accept","Accept Translation"),
17+
Binding("ctrl+s","save","Save Changes"),
18+
Binding("ctrl+g","generate","Generate Translation"),
19+
]
20+
CSS="""
21+
#status-container {
22+
height: auto;
23+
padding: 1;
24+
background: $accent-darken-2;
25+
color: $text;
26+
text-align: center;
27+
text-style: bold;
28+
}
29+
30+
#status-line {
31+
text-style: bold;
32+
}
33+
34+
#translation-container {
35+
layout: grid;
36+
grid-size: 4;
37+
grid-columns: 1fr;
38+
padding: 1;
39+
}
40+
41+
.section-label {
42+
text-align: center;
43+
background: $accent;
44+
color: $text;
45+
padding: 1;
46+
border: solid $background;
47+
}
48+
49+
.text-content {
50+
background: $surface;
51+
color: $text;
52+
padding: 1;
53+
border: solid $background;
54+
height: auto;
55+
min-height: 5;
56+
max-height: 100;
57+
overflow-y: auto;
58+
}
59+
60+
.translation-input {
61+
width: 100%;
62+
min-height: 5;
63+
height: auto;
64+
}
65+
66+
#button-container {
67+
layout: horizontal;
68+
height: auto;
69+
align: center middle;
70+
padding: 1;
71+
}
72+
"""
73+
74+
def__init__(self,po_file_path:Path):
75+
super().__init__()
76+
self.po_file_path=po_file_path
77+
self.po_file=polib.pofile(str(po_file_path))
78+
# Preserve original wrapping format
79+
self.po_file.wrapwidth=0# Disable wrapping to maintain original format
80+
self.current_entry_index=0
81+
82+
83+
@staticmethod
84+
deftranslate_text(prompt:str)->str:
85+
importtextwrap
86+
genai.configure(api_key=os.getenv('GEMINI_API'))
87+
model=genai.GenerativeModel("gemini-1.5-flash")
88+
response=model.generate_content(prompt)
89+
# Wrap text at 72 characters, which is a common standard for PO files
90+
wrapped_text=textwrap.fill(response.text,width=72)
91+
returnwrapped_text
92+
93+
defcompose(self)->ComposeResult:
94+
yieldHeader()
95+
yieldContainer(
96+
Static(id="status-line"),
97+
id="status-container"
98+
)
99+
yieldContainer(
100+
Static("Source Text",classes="section-label"),
101+
Static(id="source-text",classes="text-content"),
102+
Static("Raw Translation",classes="section-label"),
103+
Static(id="raw-translation",classes="text-content"),
104+
Static("New Translation",classes="section-label"),
105+
Input(classes="translation-input",id="translation-input"),
106+
Container(
107+
Button("Previous [←]",id="prev-btn"),
108+
Button("Accept [↵]",id="accept-btn"),
109+
Button("Next [→]",id="next-btn"),
110+
Button("Generate [^G]",id="generate-btn"),
111+
Button("Save [^S]",id="save-btn",variant="primary"),
112+
id="button-container"
113+
),
114+
id="translation-container"
115+
)
116+
yieldFooter()
117+
118+
defon_mount(self)->None:
119+
self.show_current_entry()
120+
121+
defshow_current_entry(self)->None:
122+
ifself.current_entry_index<len(self.po_file):
123+
entry=self.po_file[self.current_entry_index]
124+
status=f"File:{self.po_file_path.name} | Entry:{self.current_entry_index+1}/{len(self.po_file)}"
125+
self.query_one("#status-line").update(status)
126+
self.query_one("#source-text").update(entry.msgid)
127+
self.query_one("#raw-translation").update(entry.msgstr)
128+
129+
asyncdefon_button_pressed(self,event:Button.Pressed)->None:
130+
ifevent.button.id=="accept-btn":
131+
translation=self.query_one("#translation-input").value
132+
iftranslation:
133+
self.po_file[self.current_entry_index].msgstr=translation
134+
self.navigate_entry(1)
135+
elifevent.button.id=="next-btn":
136+
self.navigate_entry(1)
137+
elifevent.button.id=="prev-btn":
138+
self.navigate_entry(-1)
139+
elifevent.button.id=="generate-btn":
140+
entry=self.po_file[self.current_entry_index]
141+
try:
142+
prompt= ("Translate the following Python documentation into Traditional Chinese"
143+
f"for{self.po_file_path}:{entry.occurrences} with message{entry.msgid}. Ensure "
144+
"that the translation is accurate and uses appropriate technical terminology. The"
145+
" output must be in Traditional Chinese. Pay careful attention to context, idiomatic"
146+
" expressions, and any specialized vocabulary related to Python programming. Maintain "
147+
"the structure and format of the original documentation as much as possible to ensure"
148+
" clarity and usability for readers.")
149+
translation=self.translate_text(prompt)
150+
iftranslation:
151+
self.query_one("#translation-input").value=translation
152+
self.notify("Translation generated!")
153+
else:
154+
self.notify("Failed to generate translation",severity="error")
155+
exceptExceptionase:
156+
self.notify(f"Error:{str(e)}",severity="error")
157+
elifevent.button.id=="save-btn":
158+
self.po_file.save(str(self.po_file_path))
159+
try:
160+
subprocess.run(['powrap',str(self.po_file_path)],check=True)
161+
self.notify("Changes saved and wrapped successfully!")
162+
exceptsubprocess.CalledProcessError:
163+
self.notify("Save successful, but powrap failed!",severity="error")
164+
exceptFileNotFoundError:
165+
self.notify("Save successful, but powrap not found!",severity="warning")
166+
167+
defnavigate_entry(self,direction:int)->None:
168+
new_index=self.current_entry_index+direction
169+
if0<=new_index<len(self.po_file):
170+
self.current_entry_index=new_index
171+
self.show_current_entry()
172+
self.query_one("#translation-input").value=""
173+
174+
defaction_previous(self)->None:
175+
self.navigate_entry(-1)
176+
177+
defaction_next(self)->None:
178+
self.navigate_entry(1)
179+
180+
defaction_accept(self)->None:
181+
translation=self.query_one("#translation-input").value
182+
iftranslation:
183+
self.po_file[self.current_entry_index].msgstr=translation
184+
self.navigate_entry(1)
185+
186+
defaction_save(self)->None:
187+
self.po_file.save(str(self.po_file_path))
188+
try:
189+
subprocess.run(['powrap',str(self.po_file_path)],check=True)
190+
self.notify("Changes saved and wrapped successfully!")
191+
exceptsubprocess.CalledProcessError:
192+
self.notify("Save successful, but powrap failed!",severity="error")
193+
exceptFileNotFoundError:
194+
self.notify("Save successful, but powrap not found!",severity="warning")
195+
196+
defaction_generate(self)->None:
197+
entry=self.po_file[self.current_entry_index]
198+
try:
199+
prompt= ("Translate the following Python documentation into Traditional Chinese"
200+
f"for{self.po_file_path}:{entry.occurrences} with message{entry.msgid[1]}. Ensure "
201+
"that the translation is accurate and uses appropriate technical terminology. The"
202+
" output must be in Traditional Chinese. Pay careful attention to context, idiomatic"
203+
" expressions, and any specialized vocabulary related to Python programming. Maintain "
204+
"the structure and format of the original documentation as much as possible to ensure"
205+
" clarity and usability for readers.")
206+
translation=self.translate_text(prompt)
207+
iftranslation:
208+
self.query_one("#translation-input").value=translation
209+
self.notify("Translation generated!")
210+
else:
211+
self.notify("Failed to generate translation",severity="error")
212+
exceptExceptionase:
213+
self.notify(f"Error:{str(e)}",severity="error")
214+
215+
defmain(po_file_path:str):
216+
app=TranslationApp(Path(po_file_path))
217+
app.run()
218+
219+
if__name__=="__main__":
220+
importsys
221+
iflen(sys.argv)>1:
222+
main(sys.argv[1])
223+
else:
224+
print("Please provide a PO file path")

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp