Sanjam19 commited on
Commit
2bcb840
·
verified ·
1 Parent(s): d5dcf1b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -43
app.py CHANGED
@@ -1,44 +1,95 @@
 
1
  import os
2
- if not os.path.exists("data/chunks.json"):
3
- from datasets import load_dataset
4
- import json
5
- from pathlib import Path
6
- Path("data").mkdir(exist_ok=True)
7
- print("Downloading dataset...")
8
- fb = load_dataset("PatronusAI/financebench", split="train")
9
- fa = load_dataset("gbharti/finance-alpaca", split="train")
10
- chunks, entities, metadata = [], [], []
11
- for i, row in enumerate(fb):
12
- for j, ev in enumerate(row["evidence"]):
13
- text = ev.get("evidence_text","").strip()
14
- if not text: continue
15
- chunk_id = f"fb_{i:04d}_{j:02d}"
16
- chunks.append({"chunk_id":chunk_id,"company":row["company"],"doc_name":row["doc_name"],"period":row["doc_period"],"text":text,"question":row["question"],"answer":row["answer"],"source":"financebench"})
17
- entities.append({"chunk_id":chunk_id,"company":row["company"],"entities":[]})
18
- metadata.append({"chunk_id":chunk_id,"company":row["company"],"doc_name":row["doc_name"],"period":row["doc_period"],"question":row["question"],"answer":row["answer"],"source":"financebench"})
19
- def chunk_text(text, size=512, overlap=50):
20
- words = text.split()
21
- results = []
22
- start = 0
23
- while start < len(words):
24
- end = min(start+size, len(words))
25
- results.append(" ".join(words[start:end]))
26
- if end == len(words): break
27
- start += size-overlap
28
- return results
29
- target = 1_000_000
30
- current = sum(len(c["text"].split()) for c in chunks)
31
- for i, row in enumerate(fa):
32
- if current >= target: break
33
- text = row["output"].strip()
34
- if len(text.split()) < 20: continue
35
- for j, ct in enumerate(chunk_text(text)):
36
- chunk_id = f"fa_{i:05d}_{j:02d}"
37
- chunks.append({"chunk_id":chunk_id,"company":"general","doc_name":f"alpaca_{i}","period":"general","text":ct,"question":row["instruction"],"answer":row["output"],"source":"alpaca"})
38
- entities.append({"chunk_id":chunk_id,"company":"general","entities":[]})
39
- metadata.append({"chunk_id":chunk_id,"company":"general","doc_name":f"alpaca_{i}","period":"general","question":row["instruction"],"answer":row["output"],"source":"alpaca"})
40
- current += len(ct.split())
41
- json.dump(chunks, open("data/chunks.json","w",encoding="utf-8"), indent=2)
42
- json.dump(entities, open("data/entities.json","w",encoding="utf-8"), indent=2)
43
- json.dump(metadata, open("data/metadata.json","w",encoding="utf-8"), indent=2)
44
- print(f"Done. {len(chunks)} chunks")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
  import os
3
+ from fastapi import FastAPI
4
+ import gradio as gr
5
+
6
+ # ----------------------------
7
+ # FastAPI App
8
+ # ----------------------------
9
+ app = FastAPI()
10
+
11
+ @app.get("/")
12
+ def home():
13
+ return {"status": "GraphRAG running"}
14
+
15
+ # ----------------------------
16
+ # Load Data
17
+ # ----------------------------
18
+ DATA_DIR = "data"
19
+
20
+ chunks = []
21
+ entities = []
22
+ metadata = []
23
+
24
+ try:
25
+ with open(os.path.join(DATA_DIR, "chunks.json"), "r", encoding="utf-8") as f:
26
+ chunks = json.load(f)
27
+
28
+ with open(os.path.join(DATA_DIR, "entities.json"), "r", encoding="utf-8") as f:
29
+ entities = json.load(f)
30
+
31
+ with open(os.path.join(DATA_DIR, "metadata.json"), "r", encoding="utf-8") as f:
32
+ metadata = json.load(f)
33
+
34
+ print(f"Loaded {len(chunks)} chunks")
35
+
36
+ except Exception as e:
37
+ print(f"Error loading data: {e}")
38
+
39
+
40
+ # ----------------------------
41
+ # Simple Search Function
42
+ # ----------------------------
43
+ def search_query(query):
44
+ if not query.strip():
45
+ return "Enter a query"
46
+
47
+ results = []
48
+
49
+ query = query.lower()
50
+
51
+ for chunk in chunks[:500]: # limit for speed
52
+ text = chunk.get("text", "").lower()
53
+
54
+ if query in text:
55
+ results.append(
56
+ f"Company: {chunk.get('company', 'N/A')}\n"
57
+ f"Source: {chunk.get('source', 'N/A')}\n"
58
+ f"Text: {chunk.get('text', '')[:500]}"
59
+ )
60
+
61
+ if len(results) >= 5:
62
+ break
63
+
64
+ if not results:
65
+ return "No relevant results found."
66
+
67
+ return "\n\n" + ("-" * 60 + "\n\n").join(results)
68
+
69
+
70
+ # ----------------------------
71
+ # Gradio UI
72
+ # ----------------------------
73
+ with gr.Blocks() as demo:
74
+ gr.Markdown("# GraphRAG Search")
75
+
76
+ query = gr.Textbox(
77
+ label="Ask a question",
78
+ placeholder="Enter finance-related query..."
79
+ )
80
+
81
+ output = gr.Textbox(
82
+ label="Results",
83
+ lines=20
84
+ )
85
+
86
+ btn = gr.Button("Search")
87
+ btn.click(search_query, inputs=query, outputs=output)
88
+
89
+ # ----------------------------
90
+ # Launch
91
+ # ----------------------------
92
+ demo.launch(
93
+ server_name="0.0.0.0",
94
+ server_port=7860
95
+ )