-
Notifications
You must be signed in to change notification settings - Fork 0
/
myTranslate.html
520 lines (509 loc) · 21.6 KB
/
myTranslate.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="image/translate-page.ico" type="image/x-icon">
<script src="utils/vue.js"></script>
<script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="utils/md5.js"></script>
<title>Document</title>
<style>
.area_raw{
font-size: 18px;
margin-right: 8px;
width: 40%;
}
.area_ret{
font-size: 18px;
width: 40%;
}
.container {
/* 使用 Flexbox 布局 */
display: flex;
justify-content: center;
}
.container_history {
/* 使用 Flexbox 布局 */
display: flex;
justify-content: center;
max-height:500px;
overflow-y: auto;
}
.container div {
/* 如果需要添加间距,可以使用 margin 或者 flex 属性 */
margin-right: 10px;
/* 或者使用 flex 属性来调整空间分配 */
flex: 1;
}
body{
background-color: #f2f2f2;
}
@keyframes flash {
0% { background-color: white; }
50% { background-color: yellow; }
100% { background-color: white; }
}
button:hover{
background-color: orangered;
}
.fortune {
color: #888; /* 使用淡灰色文本,可调整颜色 */
opacity: 0.8; /* 降低文字的不透明度,使其看起来更淡 */
border: 1px solid #ccc; /* 添加淡灰色边框,可调整颜色和边框宽度 */
padding: 10px; /* 可选 - 添加内边距以增加内容与边框之间的间距 */
margin-top: 50px;
user-select: none;
}
.time_history{
flex: 0.2; /* 时间部分的宽度较小,分配1份flex */
margin-right: 20px; /* 与文本元素的间隔 */
text-align: center;
padding: 10px;
background-color: #f0f0f0; /* 背景色 */
border-radius: 5px; /* 圆角边框 */
font-size: 16px; /* 字体大小 */
color: #333; /* 字体颜色 */
}
.text_history{
flex: 2; /* 时间部分的宽度较小,分配1份flex */
text-align: left;
padding: 10px;
background-color: #e9ecef; /* 背景色 */
border-radius: 5px; /* 圆角边框 */
font-size: 16px; /* 字体大小 */
color: #000; /* 字体颜色 */
}
#uploadBox {
width: 13%;
height: 250px;
border: 2px dashed #007bff;
border-radius: 20px;
display: flex;
float: left;
justify-content: center;
align-items: center;
text-align: center;
background-color: #fff;
cursor: pointer;
position: relative;
transition: background-color 0.3s;
}
#uploadBox:focus {
background-color: #e3f7ff;
}
#uploadBox p {
color: #007bff;
font-size: 18px;
margin: 0;
}
#uploadBox input[type="file"] {
display: none;
}
/* 状态的不同样式 */
.waiting {
background-color: #f0f8ff;
color: #007bff;
}
.uploading {
background-color: #fff3cd;
color: #856404;
}
.completed {
background-color: #d4edda;
color: #155724;
}
.failed {
background-color: #f8d7da;
color: #721c24;
}
.ckInuploadbox{
position:absolute;
left: 1px;
top: 1px;
right: 50%;
}
</style>
</head>
<body>
<div id="app">
<div class="container">
<h2>中英互译</h2>
</div>
<div class="container">
<button @click="clearAndPaste(0)" style="font-size: 18px;border-radius: 8px; margin-right: 2px;">清空并粘贴</button>
<button @click="func_EnToCh" style="margin-right: 100px;font-size: 18px;border-radius: 8px;">翻译</button>
<button @click="func_ChToEn" style="font-size: 18px;border-radius: 8px; margin-right: 2px;">翻译</button>
<button @click="clearAndPaste(1)" style="font-size: 18px;border-radius: 8px;">清空并粘贴</button>
</div>
<div class="container">
<textarea v-model="content_english" placeholder="英文区域" autofocus="true" @keyup.enter="func_EnToCh" rows="15" class="area_raw" :style="{animation:animating_left ? 'flash 0.5s infinite':'none', backgroundColor:bgColor}"></textarea>
<br>
<textarea v-model="content_chinese" placeholder="中文区域" @keyup.enter="func_ChToEn" rows="15" class="area_ret":style="{animation:animating_right ? 'flash 0.5s infinite':'none', backgroundColor:bgColor}"></textarea>
<br>
</div>
<div class="container" style="margin-top: 5px;">
<button @click="func_copyEnglish" style="margin-right: 100px;font-size: 18px;border-radius: 8px;">复制英文</button>
<button @click="func_copyChinese" style="font-size: 18px;border-radius: 8px;">复制中文</button>
</div>
<hr>
<!-- <div class="fortune">
{{fortune}}
</div> -->
<!-- 上传框 -->
<div id="uploadBox" tabindex="0" @click="triggerFileInput" @mouseenter="isMouseInside = true" @mouseleave="isMouseInside = false" :class="uploadBoxClass">
<p>{{ uploadBoxMessage }}</p>
<input type="file" ref="fileInput" accept="image/*" @change="handleFileSelect"/>
</div>
<div class="container_history" style="width: 76%; margin-left: auto; margin-right: 3%;">
<ul>
<li v-for="(item, id) in trans_histories" :key = "id" style="display: flex;">
<div class="time_history">{{item.time}}</div>
<div class="text_history">{{item.en}}</div>
<div class="text_history">{{item.ch}}</div>
</li>
</ul>
</div>
</div>
<script src="./utils/axios.min.js"></script>
<script>
var app = new Vue({
el:'#app',
data:{
content_english:"",
content_chinese:"",
translate_ret:"",
appid:'20231220001916715',
key:'N9ZQWbmw2z0txacNk7vh',
salt:'1435660288',
from:'en',
to:'zh',
bgColor:'white',
animating_left: false,
animating_right: false,
fortune:'',
trans_histories:[],
uploadedImage: null,
isMouseInside: false,
uploadBoxClass: '',
uploadBoxMessage: '点击或拖拽上传图片,或按Ctrl+V粘贴图片',
},
methods:{
func_get(){
fetch("http://api.fanyi.baidu.com/api/trans/vip/translate?q=apple&from=en&to=zh&appid=2015063000000001&salt=1435660288&sign=f89f9594663708c1605f3d736d01d2d4")
.then(response =>{
if(!response.ok){
throw new Error('error');
}
return response.text();
})
.then(data=>{
console.log(data);
this.msg1 = data;
})
.catch(error => {
console.error('Fetch error:', error);
});
},
func_post(){
console.log('post....');
var formData = new FormData();
formData.append('postmsg', this.msg2_send);
fetch("http://182.92.208.248/strp",{
method:"POST",
body:formData,
})
.then(response =>{
if(!response.ok){
throw new Error('asdllkzlzklkz');
}
return response.text();
})
.then(data=>{
console.log(data);
this.msg2 = data;
})
.catch(error => {
console.error('Fetch error:', error);
});
},
func_EnToCh(){
var temp_msg = this.content_english.replace(/(\r\n|\n|\r)/gm, ", ");
var str1 = this.appid+temp_msg+this.salt+this.key;
var sign = MD5(str1);
$.ajax({
url: 'http://api.fanyi.baidu.com/api/trans/vip/translate',
type: 'get',
dataType: 'jsonp',
data: {
q: temp_msg,
appid: this.appid,
salt: this.salt,
from: this.from,
to: this.to,
sign: sign
},
success: (data) => {
/*这里使用箭头函数是因为要保持上下文信息,否则VUE的this将无法作用*/
var temp = data.trans_result[0].dst;
this.content_chinese = temp;
this.startAnimation(1);
this.addHistoryItem();
// this.upload_trans_info(this.content_english, this.content_chinese);
}
});
},
func_ChToEn(){
var temp_msg = this.content_chinese.replace(/(\r\n|\n|\r)/gm, ", ");
var str1 = this.appid+temp_msg+this.salt+this.key;
var sign = MD5(str1);
$.ajax({
url: 'http://api.fanyi.baidu.com/api/trans/vip/translate',
type: 'get',
dataType: 'jsonp',
data: {
q: temp_msg,
appid: this.appid,
salt: this.salt,
from: this.to,
to: this.from,
sign: sign
},
success: (data) => {
/*这里使用箭头函数是因为要保持上下文信息,否则VUE的this将无法作用*/
var temp = data.trans_result[0].dst;
this.content_english = temp;
this.startAnimation(0);
this.addHistoryItem();
}
});
},
upload_trans_info(source, dest){
var formData = new FormData();
formData.append("source", source);
// formData.append("dest", dest);
console.log("123开始上传");
//http://127.0.0.1:8000/storetrans 这里设置为向本地服务器上传时显示调用错误。。。不懂
fetch("http://182.92.208.248/strp",{
method:'post',
body:formData,
})
.then(response=>{
if(!response.ok){
throw new Error('lkz error');
}
console.log("上传成功");
})
.catch(error=>{
console.error(error);
})
},
func_copyEnglish(){
var temparea = document.createElement('textarea');
temparea.value = this.content_english;
document.body.appendChild(temparea);
temparea.select();
document.execCommand('copy');
document.body.removeChild(temparea);
console.log('已复制');
},
func_copyChinese(){
var temparea = document.createElement('textarea');
temparea.value = this.content_chinese;
document.body.appendChild(temparea);
temparea.select();
document.execCommand('copy');
document.body.removeChild(temparea);
console.log('已复制');
},
clearAndPaste(slt){
//参数slt选择清空0左边或1右边
if (slt===0){
if(navigator.clipboard){
navigator.clipboard.readText().then(clipText=>{
this.content_english = "";
this.content_english = clipText;
//直接进行翻译
this.func_EnToCh();
}).catch(err=>{
console.error("无法读取剪切板内容", err);
});
}else{
console.log("浏览器不支持剪切板clipboard API");
}
}else{
if(navigator.clipboard){
navigator.clipboard.readText().then(clipText=>{
this.content_chinese = "";
this.content_chinese = clipText;
//直接翻译
this.func_ChToEn();
}).catch(err=>{
console.error("无法读取剪切板内容", err);
});
}else{
console.log("浏览器不支持剪切板clipboard API");
}
}
},
startAnimation(slt){
if(slt==0){
//左边闪烁
this.animating_left = true;
setTimeout(() => {
this.animating_left = false;
this.bgColor = 'white';
}, 1500);
}
else{
//右边闪烁
this.animating_right = true;
setTimeout(() => {
this.animating_right = false;
this.bgColor = 'white';
}, 1500);
}
},
addHistoryItem(){
this.trans_histories.unshift({
time: this.getCurrentTime(),
en: this.content_english,
ch: this.content_chinese
})
},
getCurrentTime() {
const now = new Date(); // 获取当前时间
const hours = String(now.getHours()).padStart(2, '0'); // 获取小时,并确保是两位数
const minutes = String(now.getMinutes()).padStart(2, '0'); // 获取分钟,并确保是两位数
return `${hours}:${minutes}`; // 返回格式化的时间字符串
},
// ==========================================================
triggerFileInput() {
this.$refs.fileInput.click();
},
handleFileSelect(event) {
const file = event.target.files[0];
if (file && file.type.startsWith('image/')) {
this.uploadedImage = file;
this.updateBoxState('uploading', '正在上传...');
this.uploadImage(file);
}
},
handlePaste(event) {
if (this.isMouseInside) {
const items = event.clipboardData.items; //获取剪贴板中的内容
for (const item of items) {
if (item.type.startsWith('image/')) {
console.log('start upload and receive result...')
const blob = item.getAsFile();
this.uploadedImage = blob;
this.updateBoxState('uploading', '正在上传...');
this.uploadImage(blob);
break;
}else{
this.updateBoxState('failed', '请检查剪贴板内容');
}
}
}
},
handleDragOver(event) {
event.preventDefault();
this.uploadBoxClass = 'waiting';
},
handleDrop(event) {
event.preventDefault();
event.stopPropagation();
this.uploadBoxClass = '';
const file = event.dataTransfer.files[0];
if (file && file.type.startsWith('image/')) {
this.uploadedImage = file;
this.updateBoxState('uploading', '正在上传...');
this.uploadImage(file);
}
},
updateBoxState(state, message) {
this.uploadBoxClass = state;
this.uploadBoxMessage = message;
},
/*下面函数使用https://api.dazheng.site/ocr.html 提供的api,每个token使用次数1000,下面是其他token
// rtBIwVnDFX-PaqUSti8tlKCEBy2QtT50cosziMNjLcY=
// hPy9WVeABPXqqATIK24LkH8Xh33-322lyb0gtKkAZWw=
// 9amJ_GzpAmvNcgDWvxhehfYdTm86j3JyExr_LwVWi_A=
// hPy9WVeABPXqqATIK24LkH8Xh33-322lyb0gtKkAZWw= */
async uploadImage(image) {
try {
const form = new FormData();
form.append('file', image, image.name);
const response = await axios.post(
'https://api.dazheng.site/ocr/LGaKU8hyvLg6Ow-eLd1Fibeg0_Ga-GSRJ8-8Yu__anE=/',
form
);
const result = response.data;
await this.copyToClipboard(result.text);
console.log('该token次数剩余: ', result.remaining_calls);
this.updateBoxState('completed', '识别结果已复制到剪贴板!');
} catch (error) {
console.error('上传失败:', error);
this.updateBoxState('failed', '上传或识别失败,请重试。');
}
},
async copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
console.log('识别结果已复制到剪贴板!');
} catch (err) {
console.error('复制到剪贴板失败:', err);
alert('复制到剪贴板失败,请重试。');
}
},
},
mounted(){
window.addEventListener('paste', this.handlePaste);
window.addEventListener('dragover', this.handleDragOver);
window.addEventListener('drop', this.handleDrop);
// 获取我服务器的
// fetch("http://182.92.208.248/str_f")
// .then(response=>{
// if(!response.ok){
// throw new Error("get fail...");
// }
// return response.json();
// })
// .then(data=>{
// console.log('fortune get success!!!')
// this.fortune = data.fortune;
// })
// .catch(error=>{
// console.error('fail...')
// });
//获取公共平台的fortune
// fetch("https://v1.hitokoto.cn/",{
// method:'get',
// headers: {
// 'Content-Type': 'application/json',
// },
// })
// .then(response=>{
// return response.json();
// })
// .then(data=>{
// this.fortune = data.hitokoto+"《"+data.from+"》"+"---"+data.from_who;
// })
},
created(){
console.log("直接运行created");
// $.ajax({
// url:"http://182.92.208.248/str_f",
// type:'get',
// dataType:'jsonp',
// data:{},
// success: (data) =>{
// this.fortune = data;
// console.log("fortune获取成功");
// }
// });
}
})
</script>
</body>
</html>