berohan commited on
Commit
b8bfc68
·
verified ·
1 Parent(s): cd6c92e

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +45 -13
  2. app.py +232 -0
  3. requirements.txt +4 -0
README.md CHANGED
@@ -1,13 +1,45 @@
1
- ---
2
- title: Nlp Translate
3
- emoji: 📈
4
- colorFrom: purple
5
- colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 5.49.1
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Multipurpose NLP Web App (Gradio on Hugging Face Spaces)
2
+
3
+ An interactive Gradio app offering:
4
+ - Multi-language text translation (M2M100: 100+ languages)
5
+ - Abstractive summarization in English (DistilBART CNN)
6
+
7
+ ## Demo
8
+ Once deployed, your Space will be live at:
9
+ https://huggingface.co/spaces/<your-hf-username>/<your-space-name>
10
+
11
+ ## Features
12
+ - Translation: Choose source and target languages from 60+ common languages (backed by M2M100’s 100+ support).
13
+ - Summarization: Abstractive summaries of long text (best for English news/articles).
14
+
15
+ ## Models
16
+ - Translation: `facebook/m2m100_418M`
17
+ - Summarization: `sshleifer/distilbart-cnn-12-6`
18
+
19
+ ## Quick Start (Hugging Face Spaces)
20
+ 1. Log in at https://huggingface.co
21
+ 2. Create a new Space:
22
+ - New Space → Space SDK: Gradio
23
+ - Choose a name (e.g., `nlp-translate-summarize`)
24
+ - Hardware: CPU Basic (works; translation may be slower for long inputs)
25
+ 3. Upload these files:
26
+ - `app.py`
27
+ - `requirements.txt`
28
+ - `README.md`
29
+ 4. Wait for the build to finish. The Space will auto-start.
30
+
31
+ ## Local Development (Optional)
32
+ ```bash
33
+ python -m venv .venv && source .venv/bin/activate # or .venv\Scripts\activate on Windows
34
+ pip install -r requirements.txt
35
+ python app.py
36
+ # Visit http://127.0.0.1:7860
37
+ ```
38
+
39
+ ## Notes & Limitations
40
+ - Translation: For very long inputs, the model truncates to fit context (about ~1k tokens). Consider shorter paragraphs for best quality.
41
+ - Summarization: The chosen model is optimized for English. Non-English texts may yield weaker results.
42
+ - CPU-only inference is supported but slower; upgrading hardware on Spaces can improve latency.
43
+
44
+ ## License
45
+ MIT (adjust as needed)
app.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
4
+
5
+ # ----------------------------
6
+ # Models
7
+ # ----------------------------
8
+ # Translation model (100+ languages)
9
+ TRANS_MODEL_NAME = "facebook/m2m100_418M"
10
+
11
+ # Summarization model (English)
12
+ SUMM_MODEL_NAME = "sshleifer/distilbart-cnn-12-6"
13
+
14
+ _translation_model = None
15
+ _translation_tokenizer = None
16
+ _summarizer = None
17
+
18
+ # Curated list of widely used languages supported by M2M100.
19
+ # Keys are human-friendly names; values are M2M100 language codes.
20
+ LANGUAGES = {
21
+ "English": "en",
22
+ "French": "fr",
23
+ "German": "de",
24
+ "Spanish": "es",
25
+ "Portuguese": "pt",
26
+ "Italian": "it",
27
+ "Dutch": "nl",
28
+ "Swedish": "sv",
29
+ "Danish": "da",
30
+ "Norwegian": "no",
31
+ "Finnish": "fi",
32
+ "Polish": "pl",
33
+ "Czech": "cs",
34
+ "Slovak": "sk",
35
+ "Hungarian": "hu",
36
+ "Romanian": "ro",
37
+ "Bulgarian": "bg",
38
+ "Greek": "el",
39
+ "Turkish": "tr",
40
+ "Russian": "ru",
41
+ "Ukrainian": "uk",
42
+ "Serbian": "sr",
43
+ "Croatian": "hr",
44
+ "Slovenian": "sl",
45
+ "Albanian": "sq",
46
+ "Macedonian": "mk",
47
+ "Bosnian": "bs",
48
+ "Arabic": "ar",
49
+ "Hebrew": "he",
50
+ "Persian (Farsi)": "fa",
51
+ "Urdu": "ur",
52
+ "Hindi": "hi",
53
+ "Bengali": "bn",
54
+ "Punjabi": "pa",
55
+ "Gujarati": "gu",
56
+ "Marathi": "mr",
57
+ "Tamil": "ta",
58
+ "Telugu": "te",
59
+ "Kannada": "kn",
60
+ "Malayalam": "ml",
61
+ "Sinhala": "si",
62
+ "Nepali": "ne",
63
+ "Indonesian": "id",
64
+ "Malay": "ms",
65
+ "Vietnamese": "vi",
66
+ "Thai": "th",
67
+ "Filipino (Tagalog)": "tl",
68
+ "Chinese (Simplified)": "zh",
69
+ "Japanese": "ja",
70
+ "Korean": "ko",
71
+ "Mongolian": "mn",
72
+ "Kazakh": "kk",
73
+ "Uzbek": "uz",
74
+ "Azerbaijani": "az",
75
+ "Georgian": "ka",
76
+ "Armenian": "hy",
77
+ "Amharic": "am",
78
+ "Swahili": "sw",
79
+ "Hausa": "ha",
80
+ "Yoruba": "yo",
81
+ "Igbo": "ig",
82
+ "Zulu": "zu",
83
+ "Xhosa": "xh",
84
+ "Afrikaans": "af",
85
+ "Irish": "ga",
86
+ "Welsh": "cy",
87
+ "Basque": "eu",
88
+ "Catalan": "ca",
89
+ "Galician": "gl",
90
+ "Estonian": "et",
91
+ "Latvian": "lv",
92
+ "Lithuanian": "lt",
93
+ }
94
+
95
+ LANG_NAMES = sorted(LANGUAGES.keys())
96
+ DEFAULT_SRC = "English"
97
+ DEFAULT_TGT = "French"
98
+
99
+ def load_translation_model():
100
+ global _translation_model, _translation_tokenizer
101
+ if _translation_model is None or _translation_tokenizer is None:
102
+ _translation_tokenizer = AutoTokenizer.from_pretrained(TRANS_MODEL_NAME)
103
+ _translation_model = AutoModelForSeq2SeqLM.from_pretrained(TRANS_MODEL_NAME)
104
+ _translation_model.eval()
105
+ return _translation_model, _translation_tokenizer
106
+
107
+ def load_summarizer():
108
+ global _summarizer
109
+ if _summarizer is None:
110
+ _summarizer = pipeline(
111
+ "summarization",
112
+ model=SUMM_MODEL_NAME,
113
+ )
114
+ return _summarizer
115
+
116
+ # ----------------------------
117
+ # Inference functions
118
+ # ----------------------------
119
+ def translate(text: str, src_lang_name: str, tgt_lang_name: str, max_new_tokens: int = 256, num_beams: int = 4):
120
+ if not text or not text.strip():
121
+ return ""
122
+ if src_lang_name == tgt_lang_name:
123
+ return text
124
+
125
+ try:
126
+ model, tokenizer = load_translation_model()
127
+ src_code = LANGUAGES[src_lang_name]
128
+ tgt_code = LANGUAGES[tgt_lang_name]
129
+
130
+ tokenizer.src_lang = src_code
131
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=1024)
132
+ with torch.no_grad():
133
+ generated_tokens = model.generate(
134
+ **inputs,
135
+ forced_bos_token_id=tokenizer.get_lang_id(tgt_code),
136
+ max_new_tokens=max_new_tokens,
137
+ num_beams=num_beams,
138
+ length_penalty=1.0,
139
+ early_stopping=True,
140
+ )
141
+ out = tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
142
+ return out[0] if out else ""
143
+ except Exception as e:
144
+ return f"Error during translation: {e}"
145
+
146
+ def summarize(text: str, min_length: int = 30, max_length: int = 130):
147
+ if not text or not text.strip():
148
+ return ""
149
+ if max_length <= min_length:
150
+ return "max_length must be greater than min_length."
151
+ try:
152
+ summarizer = load_summarizer()
153
+ # The summarization pipeline will handle necessary truncation.
154
+ output = summarizer(text, min_length=min_length, max_length=max_length, do_sample=False)
155
+ return output[0]["summary_text"] if output else ""
156
+ except Exception as e:
157
+ return f"Error during summarization: {e}"
158
+
159
+ # ----------------------------
160
+ # Gradio UI
161
+ # ----------------------------
162
+ TITLE = "Multipurpose NLP: Translation and Summarization"
163
+ DESCRIPTION = """
164
+ This Space provides:
165
+ - Multi-language translation using M2M100 (100+ languages)
166
+ - Abstractive summarization in English using DistilBART CNN
167
+
168
+ Notes:
169
+ - Translation: pick source and target languages. For very long inputs, the model may truncate.
170
+ - Summarization: best for English. For long articles, try increasing max_length.
171
+ """
172
+
173
+ with gr.Blocks(title=TITLE, theme=gr.themes.Soft()) as demo:
174
+ gr.Markdown(f"# {TITLE}")
175
+ gr.Markdown(DESCRIPTION)
176
+
177
+ with gr.Tabs():
178
+ with gr.Tab("Translate"):
179
+ with gr.Row():
180
+ src = gr.Dropdown(choices=LANG_NAMES, value=DEFAULT_SRC, label="Source language")
181
+ tgt = gr.Dropdown(choices=LANG_NAMES, value=DEFAULT_TGT, label="Target language")
182
+ with gr.Row():
183
+ inp = gr.Textbox(label="Input text", lines=8, placeholder="Enter text to translate...")
184
+ with gr.Accordion("Advanced options", open=False):
185
+ max_new = gr.Slider(32, 512, value=256, step=8, label="Max new tokens")
186
+ beams = gr.Slider(1, 8, value=4, step=1, label="Beam width (higher = better but slower)")
187
+ with gr.Row():
188
+ btn_swap = gr.Button("Swap Languages ↔️", variant="secondary")
189
+ btn_translate = gr.Button("Translate", variant="primary")
190
+ out = gr.Textbox(label="Translated text", lines=8)
191
+
192
+ def _swap(a, b):
193
+ return b, a
194
+ btn_swap.click(_swap, inputs=[src, tgt], outputs=[src, tgt])
195
+ btn_translate.click(translate, inputs=[inp, src, tgt, max_new, beams], outputs=[out])
196
+
197
+ gr.Examples(
198
+ examples=[
199
+ ["Hello, how are you?", "English", "Spanish"],
200
+ ["Este libro es muy interesante.", "Spanish", "English"],
201
+ ["Je cherche un bon restaurant près d'ici.", "French", "English"],
202
+ ["机器学习正在改变世界。", "Chinese (Simplified)", "English"],
203
+ ],
204
+ inputs=[inp, src, tgt],
205
+ label="Try examples",
206
+ )
207
+
208
+ with gr.Tab("Summarize"):
209
+ s_in = gr.Textbox(label="Input text (English)", lines=12, placeholder="Paste article or long text...")
210
+ with gr.Row():
211
+ s_min = gr.Slider(10, 120, value=30, step=2, label="Min summary length")
212
+ s_max = gr.Slider(40, 300, value=130, step=2, label="Max summary length")
213
+ s_btn = gr.Button("Summarize", variant="primary")
214
+ s_out = gr.Textbox(label="Summary", lines=10)
215
+
216
+ s_btn.click(summarize, inputs=[s_in, s_min, s_max], outputs=[s_out])
217
+
218
+ gr.Examples(
219
+ examples=[
220
+ ["The Apollo program was the third United States human spaceflight program carried out by NASA, which succeeded in preparing and landing the first humans on the Moon from 1969 to 1972. It was first conceived during Dwight D. Eisenhower's administration as a three-person spacecraft to follow the one-person Project Mercury..."],
221
+ ],
222
+ inputs=[s_in],
223
+ label="Example input",
224
+ )
225
+
226
+ gr.Markdown(
227
+ "Models: facebook/m2m100_418M (translation), sshleifer/distilbart-cnn-12-6 (summarization). "
228
+ "Running on CPU may be slow for very long texts."
229
+ )
230
+
231
+ if __name__ == "__main__":
232
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio>=4.44.0
2
+ transformers>=4.43.0
3
+ torch>=2.2.0
4
+ sentencepiece>=0.1.99