oberbics commited on
Commit
ad1c1b6
·
verified ·
1 Parent(s): 18a0e17

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -65
app.py CHANGED
@@ -1,18 +1,15 @@
1
  import os
2
  os.environ["OMP_NUM_THREADS"] = "1"
3
 
4
-
5
  import gradio as gr
6
  import torch
7
  import re
8
  from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
9
  import spaces
10
 
11
-
12
  # Model configuration
13
  MODEL_ID = "oberbics/llama-3.1-newspaper-arguments-memi_2"
14
 
15
-
16
  SYSTEM_PROMPT = """You are an expert at analyzing historical texts and you hate to summarize
17
 
18
  OUTPUT FORMAT - EXACTLY these 4 XML tags and NOTHING else:
@@ -21,11 +18,12 @@ OUTPUT FORMAT - EXACTLY these 4 XML tags and NOTHING else:
21
  <explanation>Why this is an argument OR "NA"</explanation>
22
  <human_verification_needed>True OR False</human_verification_needed>
23
 
24
- <argument>It is reported from Malta that the British war-ships “Exmouth,” “Euryalus,” “Minerva,” and “Sutlej” have left for Messina. The French Government has sent two armoured ships and three destroyers to Messina. President Fallieres, Premier Clemenceau, Minister Pichon, and the Presidents of the Senate and Chamber have all sent messages of sympathy to the Italian Government. The help already proffered and accepted is insufficient for the purpose. There is pressing need of extraordinary measures of help, and provisions are in great demand. There is need of doctors, tents, clothing, and provisions for the survivors, who, deprived of all necessities, are exposed to the inclemencies of the winter weather. There is need of fire engines to cope with the flames that are raging among the ruins. The railway station has collapsed. Railway carriages have been destroyed. Almost all the railway employees are dead. The streets are no longer recognisable; they look like enormous fissures in a distant and extensive heap of ruins.</argument>
25
- <claim>Current relief efforts are inadequate and much more extensive aid is urgently needed.</claim>
26
- <explanation>The prefect explicitly argues that existing help is "insufficient" and makes a direct claim that "extraordinary measures" are needed, presenting a clear premise-conclusion structure about the inadequacy of current response.</explanation>
27
  <human_verification_needed>False</human_verification_needed>
28
 
 
29
  EXAMPLE WITHOUT ARGUMENT:
30
  <argument>NA</argument>
31
  <claim>NA</claim>
@@ -52,77 +50,102 @@ print("Loading tokenizer...")
52
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
53
  tokenizer.pad_token = tokenizer.eos_token
54
 
55
-
56
  print("Loading model...")
57
- bnb_config = BitsAndBytesConfig(
58
- load_in_4bit=True,
59
- bnb_4bit_quant_type="nf4",
60
- bnb_4bit_compute_dtype=torch.bfloat16,
61
- bnb_4bit_use_double_quant=True
62
- )
63
-
64
-
65
- model = AutoModelForCausalLM.from_pretrained(
66
- MODEL_ID,
67
- quantization_config=bnb_config,
68
- device_map="auto",
69
- torch_dtype=torch.bfloat16,
70
- trust_remote_code=True
71
- )
72
- print("Model loaded successfully!")
73
-
74
-
75
-
76
-
77
-
78
-
79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
  @spaces.GPU
82
  def extract_arguments(text, temperature=0.1):
83
  if not text or not text.strip():
84
- return "", "Please enter some text to analyze."
 
 
 
 
 
 
85
 
86
- prompt = f"""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
87
- {SYSTEM_PROMPT}<|eot_id|>
88
- <|start_header_id|>user<|end_header_id|>
89
- Extract argumentative units from historical text in their original form, no summaries. Factual reportings such as "Dem Vulkanausbruch folgten drei Sturzwellen in etwa 10 Meter Höhe" are no arguments
90
- {text}<|eot_id|>
91
- <|start_header_id|>assistant<|end_header_id|>"""
92
 
93
- inputs = tokenizer(prompt, return_tensors="pt",truncation=True, max_length=5048).to(model.device)
94
  input_length = inputs['input_ids'].shape[1]
 
 
95
  try:
96
- if temperature is None:
97
- temperature = 0.1
98
- else:
99
- temperature = float(temperature)
100
-
101
-
102
- if temperature < 0.01:
103
- temperature = 0.01
104
- elif temperature > 0.3:
105
- temperature = 0.3
106
  except:
107
  temperature = 0.1
108
-
109
-
110
  with torch.no_grad():
111
  outputs = model.generate(
112
  **inputs,
113
  max_new_tokens=8000,
114
  temperature=temperature,
115
- do_sample=True if temperature > 0.01 else False,
116
- top_p=0.9,
117
- pad_token_id=tokenizer.eos_token_id,
118
- repetition_penalty=1.1
119
  )
120
 
121
  generated_tokens = outputs[0][input_length:]
122
  response = tokenizer.decode(generated_tokens, skip_special_tokens=True)
123
-
124
-
125
- # Fix XML start
126
  if not response.startswith('<argument>'):
127
  arg_start = response.find('<argument>')
128
  if arg_start != -1:
@@ -130,9 +153,6 @@ Extract argumentative units from historical text in their original form, no summ
130
 
131
  return response
132
 
133
-
134
-
135
-
136
  # Gradio interface
137
  demo = gr.Interface(
138
  fn=extract_arguments,
@@ -147,13 +167,9 @@ demo = gr.Interface(
147
  description="Extract argumentative units from news sources",
148
  examples=[
149
  ["Reggio, January 8. Frequent shocks of earthquake were felt here dur ing the night, accompanied at times by loud subter ranean reports. A few buildings that had not been completely destroyed were further damaged. The work of reconstructing the railway is being pushed forward energetically. News has been received from Brancaleone, Catanzaro, and Palmi of earthquakes by which the inhabitants were alarmed last night", 0.1],
150
- ["Rome, January 20. At the request of the Queen, Dr. Quinco, the Court physician, has left Rome in order to super vise the medical arrangements, and the distribution of clothing and linen which has been prepared at the Quirinal under Her Majesty’s eye, in places on the Calabrian coast and inland where medical help is scarce. Rome, January 20. The controversy as to whether Messina is to be rebuilt on its former lines or finally abandoned is still in full swing. The newspapers state that a mere village will probably represent Messina for many years to come, as even should the rebuilding project eventually be decided upon, the work of clearing away the enormous quantity of debris and constructing new foundations must extend over a lengthy period. Plans for the erection of so-called earthquake-proof houses are engaging the attention of architects, but pressmen who visited the scene shortly after the disaster state that one building of this description was utterly wrecked. The Mu- sella plain, not far distant from Messina, has been selected as a site for the erection of temporary habi tations, after having been inspected by Signor Ca- sana, the Minister for War. The problem of pro viding temporary accommodation becomes daily more pressing, as the majority of the survivors refuse to leave their household goods lying under the ruins to the mercy of plunderers. Both Catania and Pa lermo, however, are crowded with refugees, and great difficulty is experienced in finding shelter for them. General Mazza, the provisional commandant at Messina, continues to send favourable reports regarding the health of the troops and survivors. Conditions at Reggio remain the same, but no fur ther rescues have been reported from there since Saturday. Milan, January 19. Signor Barzini, writing £n the Corriere de la Sera, accuses the authorities at Messina of inactivity, want of energy, and pedantry.", 0.1]
151
  ]
152
  )
153
 
154
-
155
-
156
-
157
  if __name__ == "__main__":
158
- demo.launch()
159
-
 
1
  import os
2
  os.environ["OMP_NUM_THREADS"] = "1"
3
 
 
4
  import gradio as gr
5
  import torch
6
  import re
7
  from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
8
  import spaces
9
 
 
10
  # Model configuration
11
  MODEL_ID = "oberbics/llama-3.1-newspaper-arguments-memi_2"
12
 
 
13
  SYSTEM_PROMPT = """You are an expert at analyzing historical texts and you hate to summarize
14
 
15
  OUTPUT FORMAT - EXACTLY these 4 XML tags and NOTHING else:
 
18
  <explanation>Why this is an argument OR "NA"</explanation>
19
  <human_verification_needed>True OR False</human_verification_needed>
20
 
21
+ <argument>Il giornale L'Italia moderna economica e finanziaria nel numero di oggi propone che non si facciano sottoscrizioni, le quali per quanto larghe sarebbero sempre impari ai bisogni, ma che il Parlamento stabilisca pochi centesimi addizionali per ogni lira su tutte le imposte e tasse (esclusi soltanto i dazi doganali la cui misura è vincolata da trattati di commercio).</argument>
22
+ <claim>Private subscriptions are inadequate for earthquake relief; parliamentary taxation would be more effective.</claim>
23
+ <explanation>The newspaper explicitly argues against private subscriptions as insufficient and proposes a specific alternative solution through parliamentary taxation, making a clear comparative argument about funding mechanisms.</explanation>
24
  <human_verification_needed>False</human_verification_needed>
25
 
26
+
27
  EXAMPLE WITHOUT ARGUMENT:
28
  <argument>NA</argument>
29
  <claim>NA</claim>
 
50
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
51
  tokenizer.pad_token = tokenizer.eos_token
52
 
 
53
  print("Loading model...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
+ # Try to load with bfloat16 first (best quality)
56
+ # If that fails due to memory, fall back to 8-bit quantization
57
+ try:
58
+ model = AutoModelForCausalLM.from_pretrained(
59
+ MODEL_ID,
60
+ device_map="auto",
61
+ torch_dtype=torch.bfloat16,
62
+ trust_remote_code=True
63
+ )
64
+ print("✅ Model loaded successfully in bfloat16!")
65
+ except Exception as e:
66
+ print(f"⚠️ Could not load in bfloat16: {e}")
67
+ print("Trying 8-bit quantization...")
68
+
69
+ try:
70
+ # 8-bit is much better than 4-bit
71
+ bnb_config = BitsAndBytesConfig(
72
+ load_in_8bit=True,
73
+ llm_int8_threshold=6.0
74
+ )
75
+
76
+ model = AutoModelForCausalLM.from_pretrained(
77
+ MODEL_ID,
78
+ quantization_config=bnb_config,
79
+ device_map="auto",
80
+ torch_dtype=torch.bfloat16,
81
+ trust_remote_code=True
82
+ )
83
+ print("✅ Model loaded successfully in 8-bit!")
84
+ except Exception as e:
85
+ print(f"⚠️ Could not load in 8-bit: {e}")
86
+ print("Falling back to 4-bit quantization (may reduce quality)...")
87
+
88
+ # Last resort: 4-bit quantization
89
+ bnb_config = BitsAndBytesConfig(
90
+ load_in_4bit=True,
91
+ bnb_4bit_quant_type="nf4",
92
+ bnb_4bit_compute_dtype=torch.bfloat16,
93
+ bnb_4bit_use_double_quant=True
94
+ )
95
+
96
+ model = AutoModelForCausalLM.from_pretrained(
97
+ MODEL_ID,
98
+ quantization_config=bnb_config,
99
+ device_map="auto",
100
+ torch_dtype=torch.bfloat16,
101
+ trust_remote_code=True
102
+ )
103
+ print("⚠️ Model loaded in 4-bit (quality may be reduced)")
104
 
105
  @spaces.GPU
106
  def extract_arguments(text, temperature=0.1):
107
  if not text or not text.strip():
108
+ return "Please enter some text to analyze."
109
+
110
+ # Use the same message format as the working local version
111
+ messages = [
112
+ {"role": "system", "content": SYSTEM_PROMPT},
113
+ {"role": "user", "content": f"Extract argumentative units from historical text in their original form, no summary.\n{text}"}
114
+ ]
115
 
116
+ # Use apply_chat_template - the proper way to format prompts
117
+ prompt = tokenizer.apply_chat_template(
118
+ messages,
119
+ tokenize=False,
120
+ add_generation_prompt=True
121
+ )
122
 
123
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=5048).to(model.device)
124
  input_length = inputs['input_ids'].shape[1]
125
+
126
+ # Validate temperature
127
  try:
128
+ temperature = float(temperature)
129
+ temperature = max(0.01, min(0.3, temperature))
 
 
 
 
 
 
 
 
130
  except:
131
  temperature = 0.1
132
+
133
+ # Generate with the same parameters as local version
134
  with torch.no_grad():
135
  outputs = model.generate(
136
  **inputs,
137
  max_new_tokens=8000,
138
  temperature=temperature,
139
+ top_p=0.95, # Match local version
140
+ repetition_penalty=1.15, # Match local version
141
+ do_sample=True,
142
+ pad_token_id=tokenizer.eos_token_id
143
  )
144
 
145
  generated_tokens = outputs[0][input_length:]
146
  response = tokenizer.decode(generated_tokens, skip_special_tokens=True)
147
+
148
+ # Fix XML start if needed
 
149
  if not response.startswith('<argument>'):
150
  arg_start = response.find('<argument>')
151
  if arg_start != -1:
 
153
 
154
  return response
155
 
 
 
 
156
  # Gradio interface
157
  demo = gr.Interface(
158
  fn=extract_arguments,
 
167
  description="Extract argumentative units from news sources",
168
  examples=[
169
  ["Reggio, January 8. Frequent shocks of earthquake were felt here dur ing the night, accompanied at times by loud subter ranean reports. A few buildings that had not been completely destroyed were further damaged. The work of reconstructing the railway is being pushed forward energetically. News has been received from Brancaleone, Catanzaro, and Palmi of earthquakes by which the inhabitants were alarmed last night", 0.1],
170
+ ["England ist nicht bereit lür die Olympiade 1948 » sagt Vernon Morgan, der frühere Olympialäufer und südamerikanische Rekordler über 1500 m. Wir geben nachstehendem Artikel noch Raum, ob- derer Stelle von größerem Nutzen; alle Baumatewohl es inzwischen keinem Zweifel mehr unter- rialien würden dringend zur Behebung der kataliegen wird, daß England die Olympiade durch- strophalen Wohnungsnot gebraucht, und die Nahführen wird, wenn es auch noch große Schwierig- rungsmittelversorgung sei ohnehin schon knapp gekeiten überwinden muß. nug und er) aube eine soicne Rjeseneinladung nicht. Im kommenden Sommer werden in London Sportler, Dann gibt es solche, die überhaupt gegen die offizielle Würdenträger und Besucher aus aller Welt Olympischen Spiele sind, mit der Begründung, dazu dem zweifellos größten sportlichen Ereignis der Positive, was an ihnen sei, werde bei weitem durch Welt zusammenkommen— zu den Olympischen Spie- das Negative übertroffen, und sie führten nur zu len. Seit vierzig Jahren, nämlich seit die Olymplade Internationalen Zänkereien. von 1908 in der alten White City abgehalten wurde, Dies sind in großen Zügen die verschiedenen Anhat London nicht mehr eine solche Ansammlung von sichten. Und ich als glühender Verehrer der olym-Sportsleuten aller Rassen, Farben und Glaubensbe- pischen Bewegung und als jemand, der im Sport und kenntnisse in Englands Hauptstadt gesehen. in der Sportlichkeit eines der Mittel sieht, der Welt Das erste, was heute jeder sagt, wenn er von der den Frieden zu bringen auch Ich bin der Meinung, Londoner Olympiade spricht, ist: « Soll England sie daß die Olympischen Spiele im nächsten Jahr nicht abhalten?» Wahrscheinlich wird diese Frage ebenso in London abgehalten werden sollten, häufig in den USA. und Indien um nur zwei große Daß alles nur Mögliche, was für unsere J _ OSUiher Länder zu nennen — wie In England gestellt. Meldungen aus Uebersee besagen, daß im Ausland über diese Frage ebenso viel Meinungsverschiedenheit herrscht wie in England. Im Vereinigten Königreich werden folgende Argumente geltend gemacht: « Es ist eine große Ehre für ein Land und seine Hauptstadt, wenn ihm die Olympischen Spiele zugewiesen werden. Die Nationen der Welt haben die Olympiade von 1948 London übergeben; es abzuweisen, wäre unhöflich nicht davon zu reden, daß viele Jahre darüber hingehen könnten, bis England wieder eine solche Ehre zuteil werden würde. » Viel zu wenig Menschen in der Welt sind sich aber darüber klar, wie sich das Leben heute in England abspielt, und die Besucher der Olymplade werden selbst imstande sein zu sehen, wie hart die m Krieg heimgesuchten Einwohner Großbritan < iii um den Frieden kämpfen. England ist nicht bereit für die Besucher Diejenigen, die gegen eine Abhaltung der Spiele in London sind, sagen als erstes, daß das Land nicht darauf vorbereitet sei, eine so umfangreiche sportliche Festivität abzuhalten, und die Besucher würden enttäuscht und unzufrieden mit ihren Gastgebern nach Hause zurückkehren. « Lieber niemand ins Haus einladen », sagen sie, « als ihm ein miserables Essen vorsetzen ». Sie sagen ferner, das ganze Geld, das für die Spiele ausgegeben werden soll, auch wenn die Vorführungen in einem bescheidenen uneinfachen Rahmen abgehalten werden, wäre _ an an getan werden kann, auch getan werden wird, darüber isl kein Wort zu verlieren; aber unser Land ist nicht imstande, einen Zufluß von Tausenden von Besuchern zu irgendwelchem Zweck aufzunehmen. Es ist viel zu wenig von allem da. Die Nationen waren durch die Annahme überrascht Wenn London rechtzeitig gebeten hätte, von ihm abzusehen, würde es bei den übrigen teilnehmenden Nationen volles Verständnis gefunden haben. Es gab maßgebende Leute, die über die Annahme Englands ziemlich überrascht waren. Von einem Gastgeber, der sein Diner wegen mangelnder Vorräte rechtzeitig absagt, denkt man oft besser als von einem, der keine Vorsorge trifft, und seine Gäste bittet, mit lern vorlieb zu nehmen, was gerade da ist. Es ist menschlich, nicht mit allen Begleitumständen einverstanden zu sein, und ein solcher Gastgeber könnte wohl der Ungasllichkeit geziehen werden. Anderseits kann man allerdings nicht umhin zuzugeben, daß es Ausländern gut tüte, zu sehen, wie England heute lebt. Was das Argument betrifft, daß bei den Spielen mehr Negatives als Gutes herauskäme, so ist hier nicht der rechte Ort, diese vielumstrittene und dornige Frage zu untersuchen, aber man kann zum mindesten sagen, daß die Mehrheit aller Leute in der Welt ihre Abhaltung befürwortet. Etwa vor einem Jahr stellte der « Daily Express », die am meisten verbreitete englische Tageszeitung, eine Rundfrage darüber an, ob England die Spiele Im nach", 0.1]
171
  ]
172
  )
173
 
 
 
 
174
  if __name__ == "__main__":
175
+ demo.launch()