Spaces:
Running on Zero
Running on Zero
Modified the app
Browse filesFiles changed (7)
- .gitignore+1
- 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
167 unmodified lines168169170171167 unmodified lines.DS_Storecache/167 unmodified lines168169170171172167 unmodified lines.DS_Store*.csvcache/
3 unmodified lines456789103 unmodified linescolorFrom: purplecolorTo: pinksdk: gradiosdk_version: 4.40.0app_file: app.pypinned: falselicense: apache-2.03 unmodified lines456789103 unmodified linescolorFrom: purplecolorTo: pinksdk: gradiosdk_version: 5.43.1app_file: app.pypinned: falselicense: apache-2.0
123435 unmodified lines40414243444546import spacesimport gradio as grfrom phi3_instruct_graph import MODEL_LIST, Phi3InstructGraphimport rapidjson35 unmodified linesreturn " ".join(text.split())# Main processing functions@spaces.GPUdef extract(text, model):try:model = Phi3InstructGraph(model=model)123435 unmodified lines40414243444546# import spacesimport gradio as grfrom phi3_instruct_graph import MODEL_LIST, Phi3InstructGraphimport rapidjson35 unmodified linesreturn " ".join(text.split())# Main processing functions# @spaces.GPUdef extract(text, model):try:model = Phi3InstructGraph(model=model)
12345635 unmodified lines424344454647484950131 unmodified lines18218318418518618718818919012 unmodified lines20320420520620720820933 unmodified lines2432442452462472482492502512522532542552562572583 unmodified lines26226326426526626726826927027127227327427527627727827928028128228328428528628728828929029122 unmodified lines31431531631731831932032132232332432536 unmodified lines362363364365366367368import spacesimport gradio as grfrom phi3_instruct_graph import MODEL_LIST, Phi3InstructGraphimport rapidjsonfrom pyvis.network import Networkimport networkx as nx35 unmodified lines# Main processing functions@spaces.GPUdef extract(text, model):try:model = Phi3InstructGraph(model=model)result = model.extract(text)return rapidjson.loads(result)except Exception as e:131 unmodified linesallow-top-navigation-by-user-activation allow-downloads" allowfullscreen=""allowpaymentrequest="" frameborder="0" srcdoc='{html}'></iframe>"""def process_and_visualize(text, model, progress=gr.Progress()):if not text or not model:raise gr.Error("⚠️ Both text and model must be provided.")# Check if we're processing the first example for cachingis_first_example = text == EXAMPLES[0][0]12 unmodified lines# Continue with normal processing if cache failsprogress(0, desc="Starting extraction...")json_data = extract(text, model)progress(0.5, desc="Creating entity visualization...")entities_viz = create_custom_entity_viz(json_data, text)33 unmodified linescourt hearing on August 2, 2024. The suspension follows Timberlake's arrest for driving while intoxicated (DWI)in Sag Harbor on June 18. Timberlake, who is currently on tour in Europe,pleaded not guilty to the charges.""")],[handle_text("""내 아들 민수는 내 직계 후손이자 준호의 부친으로, 태현과는 오랜 우애를 쌓아온 동료 같은 관계를 유지하며, 가문 내에서 서로의 성장에 큰 영향을 주고 있다.순자는 나의 외조모로서, 나와 태현은 물론 민수와 준호에게 한결같은 지혜와 사랑을 전해주었으며, 지영의 어머니와도 깊은 가족적 유대를 공유해왔다.태현은 단순한 형제 관계를 넘어, 현우의 친부로서 그와 굳건한 부자 관계를 이루며, 지영과는 수많은 가족 모임에서 서로의 삶에 큰 영향을 주며 단단한 인연을 만들어왔다.지영은 나의 사촌으로서, 민수와는 비공식적 친분을 통해 가문의 화합에 기여하며, 수진과는 이종사촌 이상의 특별한 우애로 서로를 지탱하는 사이이다.""")],[handle_text("""한국 영화 '기생충'은 2020년 아카데미 시상식에서 작품상, 감독상, 각본상, 국제영화상 등 4개 부문을 수상하며 역사를 새로 썼다.봉준호 감독이 연출한 이 영화는 한국 영화 최초로 칸 영화제 황금종려상도 수상했으며, 전 세계적으로 엄청난 흥행과평단의 호평을 받았다.""")]]# Function to preprocess the first example when the app starts3 unmodified linesprint("Generating cache for first example...")try:text = EXAMPLES[0][0]model = MODEL_LIST[0] if MODEL_LIST else Noneif model:# Extract datajson_data = extract(text, model)entities_viz = create_custom_entity_viz(json_data, text)graph_html = create_graph(json_data)node_count = len(json_data["nodes"])edge_count = len(json_data["edges"])stats = f"📊 Extracted {node_count} entities and {edge_count} relationships"# Save to cachecache_data = {"graph_html": graph_html,"entities_viz": entities_viz,"json_data": json_data,"stats": stats}with open(EXAMPLE_CACHE_FILE, 'wb') as f:pickle.dump(cache_data, f)print("First example cache generated successfully")return cache_dataexcept Exception as e:print(f"Error generating first example cache: {str(e)}")else:22 unmodified lineswith gr.Row():# Left panel - Input controlswith gr.Column(scale=1):input_model = gr.Dropdown(MODEL_LIST,label="🤖 Select Model",info="Choose a model to process your text",value=MODEL_LIST[0] if MODEL_LIST else None)input_text = gr.TextArea(label="📝 Input Text",36 unmodified lines# Functionalitysubmit_button.click(fn=process_and_visualize,inputs=[input_text, input_model],outputs=[output_graph, output_entity_viz, output_json, stats_output])12345635 unmodified lines424344454647484950131 unmodified lines18218318418518618718818919012 unmodified lines20320420520620720820933 unmodified lines2432442452462472482492503 unmodified lines25425525625725825926026126226326426526626726826927027127227327427527627727827928028128228322 unmodified lines30630730830931031131231331431531631736 unmodified lines354355356357358359360361import spacesimport gradio as grfrom phi3_instruct_graph import Phi3InstructGraphimport rapidjsonfrom pyvis.network import Networkimport networkx as nx35 unmodified lines# Main processing functions@spaces.GPUdef extract(text):try:model = Phi3InstructGraph()result = model.extract(text)return rapidjson.loads(result)except Exception as e:131 unmodified linesallow-top-navigation-by-user-activation allow-downloads" allowfullscreen=""allowpaymentrequest="" frameborder="0" srcdoc='{html}'></iframe>"""def process_and_visualize(text, progress=gr.Progress()):if not text:raise gr.Error("⚠️ Text must be provided!")# Check if we're processing the first example for cachingis_first_example = text == EXAMPLES[0][0]12 unmodified lines# Continue with normal processing if cache failsprogress(0, desc="Starting extraction...")json_data = extract(text)progress(0.5, desc="Creating entity visualization...")entities_viz = create_custom_entity_viz(json_data, text)33 unmodified linescourt hearing on August 2, 2024. The suspension follows Timberlake's arrest for driving while intoxicated (DWI)in Sag Harbor on June 18. Timberlake, who is currently on tour in Europe,pleaded not guilty to the charges.""")],[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.""")]]# Function to preprocess the first example when the app starts3 unmodified linesprint("Generating cache for first example...")try:text = EXAMPLES[0][0]# model = MODEL_LIST[0] if MODEL_LIST else None# if model:# Extract datajson_data = extract(text, model)entities_viz = create_custom_entity_viz(json_data, text)graph_html = create_graph(json_data)node_count = len(json_data["nodes"])edge_count = len(json_data["edges"])stats = f"📊 Extracted {node_count} entities and {edge_count} relationships"# Save to cachecache_data = {"graph_html": graph_html,"entities_viz": entities_viz,"json_data": json_data,"stats": stats}with open(EXAMPLE_CACHE_FILE, 'wb') as f:pickle.dump(cache_data, f)print("First example cache generated successfully")return cache_dataexcept Exception as e:print(f"Error generating first example cache: {str(e)}")else:22 unmodified lineswith gr.Row():# Left panel - Input controlswith gr.Column(scale=1):# input_model = gr.Dropdown(# MODEL_LIST,# label="🤖 Select Model",# info="Choose a model to process your text",# value=MODEL_LIST[0] if MODEL_LIST else None# )input_text = gr.TextArea(label="📝 Input Text",36 unmodified lines# Functionalitysubmit_button.click(fn=process_and_visualize,# inputs=[input_text, input_model],inputs=[input_text],outputs=[output_graph, output_entity_viz, output_json, stats_output])
123461 unmodified lines66676869707172import spacesimport gradio as grfrom phi3_instruct_graph import MODEL_LIST, Phi3InstructGraphimport rapidjson61 unmodified linesreturn " ".join(text.split())# Core extraction function@spaces.GPUdef extract(text, model):model = Phi3InstructGraph(model=model)try:123461 unmodified lines66676869707172# import spacesimport gradio as grfrom phi3_instruct_graph import MODEL_LIST, Phi3InstructGraphimport rapidjson61 unmodified linesreturn " ".join(text.split())# Core extraction function# @spaces.GPUdef extract(text, model):model = Phi3InstructGraph(model=model)try:
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505132 unmodified lines8485868788899017 unmodified lines108109110111112113import torchfrom transformers import AutoModelForCausalLM, AutoTokenizer, pipelinefrom textwrap import dedentfrom huggingface_hub import loginimport osfrom dotenv import load_dotenvload_dotenv()login(token=os.environ["HF_TOKEN"],)MODEL_LIST = ["EmergentMethods/Phi-3-mini-4k-instruct-graph","EmergentMethods/Phi-3-mini-128k-instruct-graph",# "EmergentMethods/Phi-3-medium-128k-instruct-graph"]torch.random.manual_seed(0)class Phi3InstructGraph:def __init__(self, model = "EmergentMethods/Phi-3-mini-4k-instruct-graph"):if model not in MODEL_LIST:raise ValueError(f"model must be one of {MODEL_LIST}")self.model_path = modelself.model = AutoModelForCausalLM.from_pretrained(self.model_path,device_map="cuda",torch_dtype="auto",trust_remote_code=True,)self.tokenizer = AutoTokenizer.from_pretrained(self.model_path)self.pipe = pipeline("text-generation",model=self.model,tokenizer=self.tokenizer,)def _generate(self, messages):generation_args = {"max_new_tokens": 2000,"return_full_text": False,"temperature": 0.1,"do_sample": False,}return self.pipe(messages, **generation_args)def _get_messages(self, text):context = dedent("""\n32 unmodified lines""")if self.model_path == "EmergentMethods/Phi-3-medium-128k-instruct-graph":# model without system messagemessages = [{"role": "user",17 unmodified linesdef extract(self, text):messages = self._get_messages(text)pipe_output = self._generate(messages)# print("pipe_output json", pipe_output[0]["generated_text"])return pipe_output[0]["generated_text"]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535432 unmodified lines8788899091929317 unmodified lines111112113114115116import osfrom textwrap import dedentfrom huggingface_hub import InferenceClientfrom dotenv import load_dotenvload_dotenv()api_token = os.environ["HF_TOKEN"]endpoint_url = os.environ["HF_API_ENDPOINT"]# Initialize the client with your endpoint URL and token.client = InferenceClient(model=endpoint_url,token=api_token)class Phi3InstructGraph:def __init__(self, model = "EmergentMethods/Phi-3-mini-4k-instruct-graph"):self.model_path = model# self.model = AutoModelForCausalLM.from_pretrained(# self.model_path,# device_map="cuda",# torch_dtype="auto",# trust_remote_code=True,# )# self.tokenizer = AutoTokenizer.from_pretrained(self.model_path)# self.pipe = pipeline(# "text-generation",# model=self.model,# tokenizer=self.tokenizer,# )def _generate(self, messages):# generation_args = {# "max_new_tokens": 2000,# "return_full_text": False,# "temperature": 0.1,# "do_sample": False,# }# Use the chat_completion methodresponse = client.chat_completion(messages=messages,max_tokens=1024,)# Access the generated textgenerated_text = response.choices[0].message.contentreturn generated_text# return self.pipe(messages, **generation_args)def _get_messages(self, text):context = dedent("""\n32 unmodified lines""")if self.model_path == "EmergentMethods/Phi-3-medium-128k-instruct-graph":# model without system message -- why??messages = [{"role": "user",17 unmodified linesdef extract(self, text):messages = self._get_messages(text)generated_text = self._generate(messages)# return pipe_output[0]["generated_text"]return generated_text
12345678910python-dotenvgradiotransformers==4.45.2load_dotenvacceleratepython-rapidjsonspacespyvisnetworkxspacy12345678910python-dotenvgradiotransformers==4.45.2python-dotenvacceleratepython-rapidjsonspacespyvisnetworkxspacy
.gitignore+1
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