File size: 2,053 Bytes
8dc7ac2
 
 
 
 
 
 
 
 
 
 
65536d2
8dc7ac2
 
65536d2
8dc7ac2
 
65536d2
8dc7ac2
 
 
 
 
 
 
 
 
 
 
 
 
 
8715fda
fe3ae8b
3ff74db
 
8dc7ac2
 
 
 
 
65536d2
8dc7ac2
 
65536d2
8dc7ac2
 
 
 
 
 
65536d2
8dc7ac2
 
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
import gradio as gr
import requests
import json
import os


LANGUAGES = ['Akan', 'Arabic', ' Assamese', 'Bambara', 'Bengali', 'Catalan', 'English', 'Spanish', ' Basque', 'French', ' Gujarati', 'Hindi', 
'Indonesian', 'Igbo', 'Kikuyu', 'Kannada', 'Ganda', 'Lingala', 'Malayalam', 'Marathi', 'Nepali', 'Chichewa', 'Oriya', 'Panjabi', 'Portuguese', 
'Kirundi', 'Kinyarwanda', 'Shona', 'Sotho', 'Swahili', 'Tamil', 'Telugu', 'Tswana', 'Tsonga', 'Twi', 'Urdu', 'Viêt Namese', 'Wolof', 'Xhosa', 
'Yoruba', 'Chinese', 'Zulu']

API_URL = "https://api-inference.huggingface.co/models/bigscience/bloom"


def translate(input, output, text):
    """Translate text from input language to output language"""

    instruction =  f"""Translation in {input}: {text.strip()}<end> Translation in {output}:""" 

    json_ = {
        "inputs": instruction,
        "parameters": {
            "return_full_text": True,
            "do_sample": False,
            "max_new_tokens": 250,
        }, 
        "options": {
            "use_cache": True,
            "wait_for_model": True,
            },
    }
    response = requests.request("POST", API_URL,  json=json_) 
    output = response.json()[0]['generated_text']
    output = output.replace(instruction, '', 1)
    search_char = output.find(f'Translation in {output}')
    return output[(search_char+len(f'Translation in {output}') if search_char != -1 else 0):].split('<end>')[0]

demo = gr.Blocks()

with demo:
  gr.Markdown("<h1><center>Translation with Bloom</center></h1>")
  gr.Markdown("<center>Translation with bloom.</center>")
  
  with gr.Row():
    input_lang = gr.Dropdown(LANGUAGES, value='English', label='Select input language')
    output_lang = gr.Dropdown(LANGUAGES, value='French', label='Select output language')

  input_text = gr.Textbox(label="Input", lines=6)  
  output_text = gr.Textbox(lines=6, label="Output")

  buton = gr.Button("translate")
  buton.click(translate, inputs=[input_lang, output_lang, input_text], outputs=output_text) 
    
demo.launch(enable_queue=True, debug=True)