vietexob commited on
Commit
b845e1d
·
1 Parent(s): 9b09229

Modified the app

Browse files
Files changed (7) hide show
  1. .gitignore +1 -0
  2. README.md +1 -1
  3. app-backup.py +2 -2
  4. app.py +40 -47
  5. main.py +2 -2
  6. phi3_instruct_graph.py +42 -39
  7. requirements.txt +2 -2
.gitignore CHANGED
@@ -168,4 +168,5 @@ __marimo__/
168
 
169
  .DS_Store
170
  *.pdf
 
171
  cache/
 
168
 
169
  .DS_Store
170
  *.pdf
171
+ *.csv
172
  cache/
README.md CHANGED
@@ -4,7 +4,7 @@ emoji: 👀
4
  colorFrom: purple
5
  colorTo: pink
6
  sdk: gradio
7
- sdk_version: 4.40.0
8
  app_file: app.py
9
  pinned: false
10
  license: apache-2.0
 
4
  colorFrom: purple
5
  colorTo: pink
6
  sdk: gradio
7
+ sdk_version: 5.43.1
8
  app_file: app.py
9
  pinned: false
10
  license: apache-2.0
app-backup.py CHANGED
@@ -1,4 +1,4 @@
1
- import spaces
2
  import gradio as gr
3
  from phi3_instruct_graph import MODEL_LIST, Phi3InstructGraph
4
  import rapidjson
@@ -40,7 +40,7 @@ def handle_text(text):
40
  return " ".join(text.split())
41
 
42
  # Main processing functions
43
- @spaces.GPU
44
  def extract(text, model):
45
  try:
46
  model = Phi3InstructGraph(model=model)
 
1
+ # import spaces
2
  import gradio as gr
3
  from phi3_instruct_graph import MODEL_LIST, Phi3InstructGraph
4
  import rapidjson
 
40
  return " ".join(text.split())
41
 
42
  # Main processing functions
43
+ # @spaces.GPU
44
  def extract(text, model):
45
  try:
46
  model = Phi3InstructGraph(model=model)
app.py CHANGED
@@ -1,6 +1,6 @@
1
  import spaces
2
  import gradio as gr
3
- from phi3_instruct_graph import MODEL_LIST, Phi3InstructGraph
4
  import rapidjson
5
  from pyvis.network import Network
6
  import networkx as nx
@@ -42,9 +42,9 @@ def handle_text(text):
42
 
43
  # Main processing functions
44
  @spaces.GPU
45
- def extract(text, model):
46
  try:
47
- model = Phi3InstructGraph(model=model)
48
  result = model.extract(text)
49
  return rapidjson.loads(result)
50
  except Exception as e:
@@ -182,9 +182,9 @@ def create_graph(json_data):
182
  allow-top-navigation-by-user-activation allow-downloads" allowfullscreen=""
183
  allowpaymentrequest="" frameborder="0" srcdoc='{html}'></iframe>"""
184
 
185
- def process_and_visualize(text, model, progress=gr.Progress()):
186
- if not text or not model:
187
- raise gr.Error("⚠️ Both text and model must be provided.")
188
 
189
  # Check if we're processing the first example for caching
190
  is_first_example = text == EXAMPLES[0][0]
@@ -203,7 +203,7 @@ def process_and_visualize(text, model, progress=gr.Progress()):
203
  # Continue with normal processing if cache fails
204
 
205
  progress(0, desc="Starting extraction...")
206
- json_data = extract(text, model)
207
 
208
  progress(0.5, desc="Creating entity visualization...")
209
  entities_viz = create_custom_entity_viz(json_data, text)
@@ -243,16 +243,8 @@ Jane, my cousin, contributes to the family's unity through her informal rapport
243
  court hearing on August 2, 2024. The suspension follows Timberlake's arrest for driving while intoxicated (DWI)
244
  in Sag Harbor on June 18. Timberlake, who is currently on tour in Europe,
245
  pleaded not guilty to the charges.""")],
246
-
247
- [handle_text(""" 아들 민수는 직계 후손이자 준호의 부친으로, 태현과는 오랜 우애를 쌓아온 동료 같은 관계를 유지하며, 가문 내에서 서로의 성장에 영향을 주고 있다.
248
- 순자는 나의 외조모로서, 나와 태현은 물론 민수와 준호에게 한결같은 지혜와 사랑을 전해주었으며, 지영의 어머니와도 깊은 가족적 유대를 공유해왔다.
249
- 태현은 단순한 형제 관계를 넘어, 현우의 친부로서 그와 굳건한 부자 관계를 이루며, 지영과는 수많은 가족 모임에서 서로의 삶에 큰 영향을 주며 단단한 인연을 만들어왔다.
250
- 지영은 나의 사촌으로서, 민수와는 비공식적 친분을 통해 가문의 화합에 기여하며, 수진과는 이종사촌 이상의 특별한 우애로 서로를 지탱하는 사이이다.
251
- """)],
252
-
253
- [handle_text("""한국 영화 '기생충'은 2020년 아카데미 시상식에서 작품상, 감독상, 각본상, 국제영화상 등 4개 부문을 수상하며 역사를 새로 썼다.
254
- 봉준호 감독이 연출한 이 영화는 한국 영화 최초로 칸 영화제 황금종려상도 수상했으며, 전 세계적으로 엄청난 흥행과
255
- 평단의 호평을 받았다.""")]
256
  ]
257
 
258
  # Function to preprocess the first example when the app starts
@@ -262,30 +254,30 @@ def generate_first_example_cache():
262
  print("Generating cache for first example...")
263
  try:
264
  text = EXAMPLES[0][0]
265
- model = MODEL_LIST[0] if MODEL_LIST else None
266
 
267
- if model:
268
- # Extract data
269
- json_data = extract(text, model)
270
- entities_viz = create_custom_entity_viz(json_data, text)
271
- graph_html = create_graph(json_data)
272
-
273
- node_count = len(json_data["nodes"])
274
- edge_count = len(json_data["edges"])
275
- stats = f"📊 Extracted {node_count} entities and {edge_count} relationships"
276
-
277
- # Save to cache
278
- cache_data = {
279
- "graph_html": graph_html,
280
- "entities_viz": entities_viz,
281
- "json_data": json_data,
282
- "stats": stats
283
- }
284
- with open(EXAMPLE_CACHE_FILE, 'wb') as f:
285
- pickle.dump(cache_data, f)
286
-
287
- print("First example cache generated successfully")
288
- return cache_data
289
  except Exception as e:
290
  print(f"Error generating first example cache: {str(e)}")
291
  else:
@@ -314,12 +306,12 @@ def create_ui():
314
  with gr.Row():
315
  # Left panel - Input controls
316
  with gr.Column(scale=1):
317
- input_model = gr.Dropdown(
318
- MODEL_LIST,
319
- label="🤖 Select Model",
320
- info="Choose a model to process your text",
321
- value=MODEL_LIST[0] if MODEL_LIST else None
322
- )
323
 
324
  input_text = gr.TextArea(
325
  label="📝 Input Text",
@@ -362,7 +354,8 @@ def create_ui():
362
  # Functionality
363
  submit_button.click(
364
  fn=process_and_visualize,
365
- inputs=[input_text, input_model],
 
366
  outputs=[output_graph, output_entity_viz, output_json, stats_output]
367
  )
368
 
 
1
  import spaces
2
  import gradio as gr
3
+ from phi3_instruct_graph import Phi3InstructGraph
4
  import rapidjson
5
  from pyvis.network import Network
6
  import networkx as nx
 
42
 
43
  # Main processing functions
44
  @spaces.GPU
45
+ def extract(text):
46
  try:
47
+ model = Phi3InstructGraph()
48
  result = model.extract(text)
49
  return rapidjson.loads(result)
50
  except Exception as e:
 
182
  allow-top-navigation-by-user-activation allow-downloads" allowfullscreen=""
183
  allowpaymentrequest="" frameborder="0" srcdoc='{html}'></iframe>"""
184
 
185
+ def process_and_visualize(text, progress=gr.Progress()):
186
+ if not text:
187
+ raise gr.Error("⚠️ Text must be provided!")
188
 
189
  # Check if we're processing the first example for caching
190
  is_first_example = text == EXAMPLES[0][0]
 
203
  # Continue with normal processing if cache fails
204
 
205
  progress(0, desc="Starting extraction...")
206
+ json_data = extract(text)
207
 
208
  progress(0.5, desc="Creating entity visualization...")
209
  entities_viz = create_custom_entity_viz(json_data, text)
 
243
  court hearing on August 2, 2024. The suspension follows Timberlake's arrest for driving while intoxicated (DWI)
244
  in Sag Harbor on June 18. Timberlake, who is currently on tour in Europe,
245
  pleaded not guilty to the charges.""")],
246
+
247
+ [handle_text("""The family of Azerbaijan President Ilham Aliyev leads a charmed, glamorous life, thanks in part to financial interests in almost every sector of the economy. His wife, Mehriban, comes from the privileged and powerful Pashayev family that owns banks, insurance and construction companies, a television station and a line of cosmetics. She has led the Heydar Aliyev Foundation, Azerbaijan’s pre-eminent charity behind the construction of schools, hospitals and the country’s major sports complex. Their eldest daughter, Leyla, editor of Baku magazine, and her sister, Arzu, have financial stakes in a firm that won rights to mine for gold in the western village of Chovdar and Azerfon, the country’s largest mobile phone business. Arzu is also a significant shareholder in SW Holding, which controls nearly every operation related to Azerbaijan Airlines (“Azal”), from meals to airport taxis. Both sisters and brother Heydar own property in Dubai valued at roughly $75 million in 2010; Heydar is the legal owner of nine luxury mansions in Dubai purchased for some $44 million.""")]
 
 
 
 
 
 
 
 
248
  ]
249
 
250
  # Function to preprocess the first example when the app starts
 
254
  print("Generating cache for first example...")
255
  try:
256
  text = EXAMPLES[0][0]
257
+ # model = MODEL_LIST[0] if MODEL_LIST else None
258
 
259
+ # if model:
260
+ # Extract data
261
+ json_data = extract(text, model)
262
+ entities_viz = create_custom_entity_viz(json_data, text)
263
+ graph_html = create_graph(json_data)
264
+
265
+ node_count = len(json_data["nodes"])
266
+ edge_count = len(json_data["edges"])
267
+ stats = f"📊 Extracted {node_count} entities and {edge_count} relationships"
268
+
269
+ # Save to cache
270
+ cache_data = {
271
+ "graph_html": graph_html,
272
+ "entities_viz": entities_viz,
273
+ "json_data": json_data,
274
+ "stats": stats
275
+ }
276
+ with open(EXAMPLE_CACHE_FILE, 'wb') as f:
277
+ pickle.dump(cache_data, f)
278
+
279
+ print("First example cache generated successfully")
280
+ return cache_data
281
  except Exception as e:
282
  print(f"Error generating first example cache: {str(e)}")
283
  else:
 
306
  with gr.Row():
307
  # Left panel - Input controls
308
  with gr.Column(scale=1):
309
+ # input_model = gr.Dropdown(
310
+ # MODEL_LIST,
311
+ # label="🤖 Select Model",
312
+ # info="Choose a model to process your text",
313
+ # value=MODEL_LIST[0] if MODEL_LIST else None
314
+ # )
315
 
316
  input_text = gr.TextArea(
317
  label="📝 Input Text",
 
354
  # Functionality
355
  submit_button.click(
356
  fn=process_and_visualize,
357
+ # inputs=[input_text, input_model],
358
+ inputs=[input_text],
359
  outputs=[output_graph, output_entity_viz, output_json, stats_output]
360
  )
361
 
main.py CHANGED
@@ -1,4 +1,4 @@
1
- import spaces
2
  import gradio as gr
3
  from phi3_instruct_graph import MODEL_LIST, Phi3InstructGraph
4
  import rapidjson
@@ -66,7 +66,7 @@ def handle_text(text):
66
  return " ".join(text.split())
67
 
68
  # Core extraction function
69
- @spaces.GPU
70
  def extract(text, model):
71
  model = Phi3InstructGraph(model=model)
72
  try:
 
1
+ # import spaces
2
  import gradio as gr
3
  from phi3_instruct_graph import MODEL_LIST, Phi3InstructGraph
4
  import rapidjson
 
66
  return " ".join(text.split())
67
 
68
  # Core extraction function
69
+ # @spaces.GPU
70
  def extract(text, model):
71
  model = Phi3InstructGraph(model=model)
72
  try:
phi3_instruct_graph.py CHANGED
@@ -1,51 +1,54 @@
1
- import torch
2
- from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
3
- from textwrap import dedent
4
- from huggingface_hub import login
5
  import os
 
 
 
6
  from dotenv import load_dotenv
7
 
8
  load_dotenv()
9
- login(
10
- token=os.environ["HF_TOKEN"],
11
- )
12
 
13
- MODEL_LIST = [
14
- "EmergentMethods/Phi-3-mini-4k-instruct-graph",
15
- "EmergentMethods/Phi-3-mini-128k-instruct-graph",
16
- # "EmergentMethods/Phi-3-medium-128k-instruct-graph"
17
- ]
18
-
19
- torch.random.manual_seed(0)
20
 
21
  class Phi3InstructGraph:
22
  def __init__(self, model = "EmergentMethods/Phi-3-mini-4k-instruct-graph"):
23
- if model not in MODEL_LIST:
24
- raise ValueError(f"model must be one of {MODEL_LIST}")
25
 
26
  self.model_path = model
27
- self.model = AutoModelForCausalLM.from_pretrained(
28
- self.model_path,
29
- device_map="cuda",
30
- torch_dtype="auto",
31
- trust_remote_code=True,
32
- )
33
- self.tokenizer = AutoTokenizer.from_pretrained(self.model_path)
34
- self.pipe = pipeline(
35
- "text-generation",
36
- model=self.model,
37
- tokenizer=self.tokenizer,
38
- )
39
 
40
  def _generate(self, messages):
41
- generation_args = {
42
- "max_new_tokens": 2000,
43
- "return_full_text": False,
44
- "temperature": 0.1,
45
- "do_sample": False,
46
- }
 
 
 
 
 
 
47
 
48
- return self.pipe(messages, **generation_args)
 
 
 
49
 
50
  def _get_messages(self, text):
51
  context = dedent("""\n
@@ -84,7 +87,7 @@ class Phi3InstructGraph:
84
  """)
85
 
86
  if self.model_path == "EmergentMethods/Phi-3-medium-128k-instruct-graph":
87
- # model without system message
88
  messages = [
89
  {
90
  "role": "user",
@@ -108,6 +111,6 @@ class Phi3InstructGraph:
108
 
109
  def extract(self, text):
110
  messages = self._get_messages(text)
111
- pipe_output = self._generate(messages)
112
- # print("pipe_output json", pipe_output[0]["generated_text"])
113
- return pipe_output[0]["generated_text"]
 
 
 
 
 
1
  import os
2
+ from textwrap import dedent
3
+
4
+ from huggingface_hub import InferenceClient
5
  from dotenv import load_dotenv
6
 
7
  load_dotenv()
8
+ api_token = os.environ["HF_TOKEN"]
9
+ endpoint_url = os.environ["HF_API_ENDPOINT"]
 
10
 
11
+ # Initialize the client with your endpoint URL and token.
12
+ client = InferenceClient(
13
+ model=endpoint_url,
14
+ token=api_token
15
+ )
 
 
16
 
17
  class Phi3InstructGraph:
18
  def __init__(self, model = "EmergentMethods/Phi-3-mini-4k-instruct-graph"):
 
 
19
 
20
  self.model_path = model
21
+ # self.model = AutoModelForCausalLM.from_pretrained(
22
+ # self.model_path,
23
+ # device_map="cuda",
24
+ # torch_dtype="auto",
25
+ # trust_remote_code=True,
26
+ # )
27
+ # self.tokenizer = AutoTokenizer.from_pretrained(self.model_path)
28
+ # self.pipe = pipeline(
29
+ # "text-generation",
30
+ # model=self.model,
31
+ # tokenizer=self.tokenizer,
32
+ # )
33
 
34
  def _generate(self, messages):
35
+ # generation_args = {
36
+ # "max_new_tokens": 2000,
37
+ # "return_full_text": False,
38
+ # "temperature": 0.1,
39
+ # "do_sample": False,
40
+ # }
41
+
42
+ # Use the chat_completion method
43
+ response = client.chat_completion(
44
+ messages=messages,
45
+ max_tokens=1024,
46
+ )
47
 
48
+ # Access the generated text
49
+ generated_text = response.choices[0].message.content
50
+ return generated_text
51
+ # return self.pipe(messages, **generation_args)
52
 
53
  def _get_messages(self, text):
54
  context = dedent("""\n
 
87
  """)
88
 
89
  if self.model_path == "EmergentMethods/Phi-3-medium-128k-instruct-graph":
90
+ # model without system message -- why??
91
  messages = [
92
  {
93
  "role": "user",
 
111
 
112
  def extract(self, text):
113
  messages = self._get_messages(text)
114
+ generated_text = self._generate(messages)
115
+ # return pipe_output[0]["generated_text"]
116
+ return generated_text
requirements.txt CHANGED
@@ -1,10 +1,10 @@
1
  python-dotenv
2
  gradio
3
  transformers==4.45.2
4
- load_dotenv
5
  accelerate
6
  python-rapidjson
7
  spaces
8
  pyvis
9
  networkx
10
- spacy
 
1
  python-dotenv
2
  gradio
3
  transformers==4.45.2
4
+ python-dotenv
5
  accelerate
6
  python-rapidjson
7
  spaces
8
  pyvis
9
  networkx
10
+ spacy