Spaces:
Running
on
Zero
Running
on
Zero
Modified the app
Browse files- .gitignore +1 -0
- README.md +1 -1
- app-backup.py +2 -2
- app.py +40 -47
- main.py +2 -2
- phi3_instruct_graph.py +42 -39
- 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:
|
| 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
|
| 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
|
| 46 |
try:
|
| 47 |
-
model = Phi3InstructGraph(
|
| 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,
|
| 186 |
-
if not text
|
| 187 |
-
raise gr.Error("⚠️
|
| 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
|
| 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 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 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 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 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 |
-
|
| 10 |
-
|
| 11 |
-
)
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 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 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
)
|
| 33 |
-
self.tokenizer = AutoTokenizer.from_pretrained(self.model_path)
|
| 34 |
-
self.pipe = pipeline(
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
)
|
| 39 |
|
| 40 |
def _generate(self, messages):
|
| 41 |
-
generation_args = {
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 112 |
-
#
|
| 113 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 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
|