javi8979 commited on
Commit
b96433e
verified
1 Parent(s): 4de4cdd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -50
app.py CHANGED
@@ -24,61 +24,52 @@ languages = sorted([ 'Aragonese', 'Asturian', 'Basque', 'Bulgarian', 'Catalan',
24
  def generate_output(task, source, target, input_text, mt_text=None):
25
  date_string = datetime.today().strftime('%Y-%m-%d')
26
 
27
- if task == "Translation":
28
- prompt = f"Translate the following text from {source} into {target}.\n{source}: {input_text.strip()} \n{target}:"
29
- elif task == "Post-editing":
30
- if not mt_text:
31
- return "Please provide machine translation (MT) for post-editing.", ""
32
- prompt = f"Please fix any mistakes in the following {source}-{target} machine translation or keep it unedited if it's correct.\nSource: {input_text.strip()} \nMT: {mt_text.strip()} \nCorrected:"
33
- elif task == "Document translation":
34
- prompt = f"Please translate this text from {source} into {target}.\n{source}: {input_text.strip()}\n{target}:"
35
- elif task == "Grammar checker":
36
- prompt = f"Please fix any mistakes in the following {source} sentence or keep it unedited if it's correct.\nSentence: {input_text.strip()} \nCorrected:"
37
- elif task == "Named-entity recognition":
38
- prompt = """Analyse the following tokenized text and mark the tokens containing named entities.
39
- Use the following annotation guidelines with these tags for named entities:
40
- - ORG (Refers to named groups or organizations)
41
- - PER (Refers to individual people or named groups of people)
42
- - LOC (Refers to physical places or natural landmarks)
43
- - MISC (Refers to entities that don't fit into standard categories).
44
- Prepend B- to the first token of a given entity and I- to the remaining ones if they exist.
45
- If a token is not a named entity, label it as O.
46
- Input: """ + str(input_text.strip()) + "\nMarked:"
47
 
48
- messages = [{"role": "user", "content": prompt}]
49
- final_prompt = tokenizer.apply_chat_template(
50
- messages,
51
- tokenize=False,
52
- add_generation_prompt=True,
53
- date_string=date_string
54
- )
55
-
56
- inputs = tokenizer(final_prompt, return_tensors="pt", add_special_tokens=False).to(model.device)
57
- input_length = inputs.input_ids.shape[1]
58
-
59
- output = model.generate(
60
- input_ids=inputs.input_ids,
61
- max_new_tokens=512,
62
- early_stopping=True,
63
- num_beams=5
64
- )
65
-
66
- decoded = tokenizer.decode(output[0, input_length:], skip_special_tokens=True).strip()
67
- return decoded, ""
68
-
69
- doc_level_example = """President Donald Trump, who campaigned on promises to crack down on illegal immigration, has raised alarms in the U.S. dairy industry with his threat to impose 25% tariffs on Mexico and Canada by February 2025. This move is part of a broader strategy to declare a national emergency at the southern border to halt illegal migration completely.
70
- However, the implications for the agriculture sector, particularly dairy, are significant. Approximately half of the U.S. dairy industry's workforce consists of immigrant labor, many of whom are undocumented. The National Milk Producers Federation estimates that removing immigrant workers could decimate the dairy herd by 2.1 million cows and slash milk production by nearly 50 billion pounds, leading to a dramatic 90.4% increase in milk prices.
71
- The complex perspectives of Americans on undocumented workers were highlighted in a Pew Research Center study. While 64% of U.S. adults support legal pathways for undocumented immigrants, 35% oppose it鈥攁 gap that has been narrowing recently. Factors influencing public opinion include the belief that immigrants should have jobs and pass security checks, contrasted by concerns about lawbreakers being rewarded, fairness for legal migrants, and resource allocation.
72
- According to Zach Rutledge, an agricultural economist at Michigan State University, as nations grow wealthier, their labor forces transition away from agriculture toward sectors like services and manufacturing. This shift has led to the U.S. relying heavily on immigrant labor for agricultural work. Domestic workers, even with employment taxes, may cost $15 to $25 an hour, while H-2A visa program workers might cost $25 to $30 an hour, accounting for additional housing expenses.
73
- The National Milk Producers Federation has been vocal in advocating for changes to the H-2A visa program, which outside of its current seasonal limitations, does not support the dairy industry's year-round labor needs. Executive vice-president Jaime Castaneda reiterated the need for legislative clarity to address the undocumented workforce issues in dairy farming.
74
- The Farm Workforce Modernization Act of 2023, which could grant legal status to certain undocumented farmworkers, has been stalled in Congress, despite acknowledgment of the sector's importance to feeding America. The need for coordinated legislative efforts to ensure both border security and labor market stability is imperative moving forward."""
 
 
 
 
 
 
 
 
 
 
 
75
 
76
  with gr.Blocks() as demo:
77
  gr.Markdown("# 馃 SalamandraTA 7B - Multitask Demo")
78
  gr.Markdown("Explore the translation, grammar correction, NER and post-editing capabilities of the SalamandraTA 7B model.")
79
 
80
  with gr.Row():
81
- task_selector = gr.Radio(["Translation", "Document translation", "Post-editing", "Grammar checker", "Named-entity recognition"], value="Translation", label="Select Task")
82
 
83
  with gr.Row():
84
  source_lang = gr.Dropdown(choices=languages, value="Catalan", label="Source Language")
@@ -97,8 +88,6 @@ with gr.Blocks() as demo:
97
  ["Translation", "Catalan", "Galician", "Als antics egipcis del per铆ode de l'Imperi Nou els fascinaven els monuments dels seus predecessors, que llavors tenien m茅s de mil anys.", ""],
98
  ["Post-editing", "Catalan", "English", "Rafael Nadal i Maria Magdalena van inspirar a una generaci贸 sencera.", "Rafael Christmas and Maria the Muffin inspired an entire generation each in their own way."],
99
  ["Grammar checker", "Catalan", "", "Entonses, el meu jefe m鈥檋a dit que he de treballar els fins de setmana.", ""],
100
- ["Named-entity recognition", "", "", "['La', 'defensa', 'del', 'antiguo', 'responsable', 'de', 'la', 'RFEF', 'confirma', 'que', 'interpondr谩', 'un', 'recurso.']", ""],
101
- ["Document translation", "English", "Asturian", doc_level_example, ""]
102
  ],
103
  inputs=[task_selector, source_lang, target_lang, input_textbox, mt_textbox]
104
  )
 
24
  def generate_output(task, source, target, input_text, mt_text=None):
25
  date_string = datetime.today().strftime('%Y-%m-%d')
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
+ sentences = input_text.split('\n')
29
+ sentences = [s for s in sentences if len(s.strip()) > 0]
30
+ generated_text = []
31
+
32
+ for sentence in sentences:
33
+ sentence = sentence.strip()
34
+
35
+ if task == "Translation":
36
+ prompt = f"Translate the following text from {source} into {target}.\n{source}: {sentence.strip()} \n{target}:"
37
+ elif task == "Post-editing":
38
+ if not mt_text:
39
+ return "Please provide machine translation (MT) for post-editing.", ""
40
+ prompt = f"Please fix any mistakes in the following {source}-{target} machine translation or keep it unedited if it's correct.\nSource: {sentence.strip()} \nMT: {mt_text.strip()} \nCorrected:"
41
+ elif task == "Grammar checker":
42
+ prompt = f"Please fix any mistakes in the following {source} sentence or keep it unedited if it's correct.\nSentence: {sentence.strip()} \nCorrected:"
43
+
44
+ messages = [{"role": "user", "content": prompt}]
45
+ final_prompt = tokenizer.apply_chat_template(
46
+ messages,
47
+ tokenize=False,
48
+ add_generation_prompt=True,
49
+ date_string=date_string
50
+ )
51
+
52
+ inputs = tokenizer(final_prompt, return_tensors="pt", add_special_tokens=False).to(model.device)
53
+ input_length = inputs.input_ids.shape[1]
54
+
55
+ output = model.generate(
56
+ input_ids=inputs.input_ids,
57
+ max_new_tokens=4000,
58
+ early_stopping=True,
59
+ num_beams=5
60
+ )
61
+
62
+ decoded = tokenizer.decode(output[0, input_length:], skip_special_tokens=True).strip()
63
+ generated_text.append(decoded)
64
+
65
+ return '\n'.join(generated_text), ""
66
 
67
  with gr.Blocks() as demo:
68
  gr.Markdown("# 馃 SalamandraTA 7B - Multitask Demo")
69
  gr.Markdown("Explore the translation, grammar correction, NER and post-editing capabilities of the SalamandraTA 7B model.")
70
 
71
  with gr.Row():
72
+ task_selector = gr.Radio(["Translation", "Post-editing", "Grammar checker"], value="Translation", label="Select Task")
73
 
74
  with gr.Row():
75
  source_lang = gr.Dropdown(choices=languages, value="Catalan", label="Source Language")
 
88
  ["Translation", "Catalan", "Galician", "Als antics egipcis del per铆ode de l'Imperi Nou els fascinaven els monuments dels seus predecessors, que llavors tenien m茅s de mil anys.", ""],
89
  ["Post-editing", "Catalan", "English", "Rafael Nadal i Maria Magdalena van inspirar a una generaci贸 sencera.", "Rafael Christmas and Maria the Muffin inspired an entire generation each in their own way."],
90
  ["Grammar checker", "Catalan", "", "Entonses, el meu jefe m鈥檋a dit que he de treballar els fins de setmana.", ""],
 
 
91
  ],
92
  inputs=[task_selector, source_lang, target_lang, input_textbox, mt_textbox]
93
  )