OzoneAsai commited on
Commit
1c5c910
1 Parent(s): 5c32f97

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -37
app.py CHANGED
@@ -1,47 +1,116 @@
1
  import streamlit as st
2
  import pandas as pd
3
  from transformers import pipeline
 
4
 
5
- # transformers パイプラインのインポート
6
- fugu_translator_enja = pipeline("translation", model="staka/fugumt-en-ja")
7
- fugu_translator_jaen = pipeline("translation",model='staka/fugumt-ja-en')
8
- zhja_translator = pipeline("translation",model="Helsinki-NLP/opus-mt-tc-big-zh-ja")
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- # Streamlit アプリケーション
11
- st.title("Multi-Language Translator")
12
 
13
- # st.session_state で session-specific state を作成
14
- if 'session_models' not in st.session_state:
15
- st.session_state.session_models = {
16
- 'enja': fugu_translator_enja,
17
- 'jaen': fugu_translator_jaen,
18
- 'zhja': zhja_translator
19
- }
 
20
 
21
- # 初期化
 
 
22
  if 'csv_created' not in st.session_state:
23
  st.session_state.csv_created = False
24
 
25
- # デフォルトの入力値
26
- default_model = 'enja'
27
- default_text = ''
28
-
29
- # ユーザー入力の取得
30
- model = st.selectbox("モデル", ['enja', 'jaen', 'zhja'], index=0, key='model')
31
- text = st.text_area("入力テキスト", default_text)
32
-
33
- # 翻訳ボタンが押されたときの処理
34
- if st.button("翻訳する"):
35
- # Perform translation
36
- result = st.session_state.session_models[model](text)[0]['translation_text']
37
-
38
- # Display the result
39
- st.write(f"翻訳結果: {result}")
40
-
41
- # Save the data to a CSV file
42
- data = {'ID': [1], 'Original Text': [text], 'Result': [result]}
43
- df = pd.DataFrame(data)
44
- df.to_csv('translation_data.csv', mode='a', header=not st.session_state.csv_created, index=False)
45
-
46
- # Update the CSV creation flag
47
- st.session_state.csv_created = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import pandas as pd
3
  from transformers import pipeline
4
+ from datetime import datetime
5
 
6
+ # ================================
7
+ # Cache the translation pipelines
8
+ # ================================
9
+ @st.cache_resource
10
+ def load_translation_pipelines():
11
+ """
12
+ Load and cache translation pipelines to avoid reloading on every interaction.
13
+ """
14
+ try:
15
+ enja = pipeline("translation", model="staka/fugumt-en-ja")
16
+ jaen = pipeline("translation", model="staka/fugumt-ja-en")
17
+ zhja = pipeline("translation", model="Helsinki-NLP/opus-mt-tc-big-zh-ja")
18
+ return {'enja': enja, 'jaen': jaen, 'zhja': zhja}
19
+ except Exception as e:
20
+ st.error(f"Error loading translation models: {e}")
21
+ return {}
22
 
23
+ # Load the translation models
24
+ session_models = load_translation_pipelines()
25
 
26
+ # ================================
27
+ # Streamlit Application Layout
28
+ # ================================
29
+ st.set_page_config(
30
+ page_title="Multi-Language Translator",
31
+ layout="centered",
32
+ initial_sidebar_state="auto",
33
+ )
34
 
35
+ st.title("🌐 Multi-Language Translator")
36
+
37
+ # Initialize session state for CSV creation flag
38
  if 'csv_created' not in st.session_state:
39
  st.session_state.csv_created = False
40
 
41
+ # ================================
42
+ # User Input Section
43
+ # ================================
44
+ st.header("🔤 Enter Text to Translate")
45
+
46
+ # Model selection
47
+ model_options = {
48
+ 'English to Japanese': 'enja',
49
+ 'Japanese to English': 'jaen',
50
+ 'Chinese to Japanese': 'zhja'
51
+ }
52
+ model_display = list(model_options.keys())
53
+ model_keys = list(model_options.values())
54
+
55
+ selected_model_display = st.selectbox("Select Translation Model", model_display, index=0)
56
+ selected_model = model_options[selected_model_display]
57
+
58
+ # Text input
59
+ text = st.text_area("Input Text", height=150)
60
+
61
+ # ================================
62
+ # Translation and Output
63
+ # ================================
64
+ if st.button("🚀 Translate"):
65
+ if not text.strip():
66
+ st.warning("Please enter text to translate.")
67
+ elif selected_model not in session_models:
68
+ st.error("Selected translation model is not available.")
69
+ else:
70
+ with st.spinner("Translating..."):
71
+ try:
72
+ translator = session_models[selected_model]
73
+ translation = translator(text)[0]['translation_text']
74
+ st.success("Translation Successful!")
75
+ st.subheader("📝 Translation Result")
76
+ st.write(translation)
77
+
78
+ # Prepare data for CSV
79
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
80
+ data = {
81
+ 'Timestamp': [timestamp],
82
+ 'Model': [selected_model_display],
83
+ 'Original Text': [text],
84
+ 'Translated Text': [translation]
85
+ }
86
+ df = pd.DataFrame(data)
87
+
88
+ # Save to CSV
89
+ csv_file = 'translation_data.csv'
90
+ if not st.session_state.csv_created:
91
+ df.to_csv(csv_file, mode='w', header=True, index=False)
92
+ st.session_state.csv_created = True
93
+ else:
94
+ df.to_csv(csv_file, mode='a', header=False, index=False)
95
+
96
+ st.info(f"Translation saved to `{csv_file}`.")
97
+ except Exception as e:
98
+ st.error(f"An error occurred during translation: {e}")
99
+
100
+ # ================================
101
+ # Optional: Download Translation Data
102
+ # ================================
103
+ if st.button("📥 Download Translation Data"):
104
+ try:
105
+ df = pd.read_csv('translation_data.csv')
106
+ csv = df.to_csv(index=False).encode('utf-8')
107
+ st.download_button(
108
+ label="Download CSV",
109
+ data=csv,
110
+ file_name='translation_data.csv',
111
+ mime='text/csv',
112
+ )
113
+ except FileNotFoundError:
114
+ st.warning("No translation data available to download.")
115
+ except Exception as e:
116
+ st.error(f"An error occurred while preparing the download: {e}")