Spaces:
Sleeping
Sleeping
Update inference.py
Browse files- inference.py +35 -56
inference.py
CHANGED
@@ -1,57 +1,36 @@
|
|
|
|
|
|
1 |
import torch
|
2 |
-
from
|
3 |
-
from
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
def get_gpt_response(prompt, option1, option2):
|
37 |
-
import openai
|
38 |
-
import os
|
39 |
-
openai.api_key = os.getenv("OPENAI_API_KEY")
|
40 |
-
|
41 |
-
full_prompt = (
|
42 |
-
f"Question: {prompt}\n"
|
43 |
-
f"Option 1: {option1}\n"
|
44 |
-
f"Option 2: {option2}\n"
|
45 |
-
"Which option makes more sense and why?"
|
46 |
-
)
|
47 |
-
|
48 |
-
try:
|
49 |
-
response = openai.ChatCompletion.create(
|
50 |
-
model="gpt-3.5-turbo",
|
51 |
-
messages=[
|
52 |
-
{"role": "user", "content": full_prompt}
|
53 |
-
]
|
54 |
-
)
|
55 |
-
return response.choices[0].message["content"].strip()
|
56 |
-
except Exception as e:
|
57 |
-
return f"GPT Error: {e}"
|
|
|
1 |
+
import os
|
2 |
+
import faiss
|
3 |
import torch
|
4 |
+
from transformers import AutoTokenizer, AutoModel
|
5 |
+
from sentence_transformers import SentenceTransformer
|
6 |
+
from PyPDF2 import PdfReader
|
7 |
+
|
8 |
+
class RAGRetriever:
|
9 |
+
def __init__(self):
|
10 |
+
self.encoder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
11 |
+
self.index = faiss.IndexFlatL2(384)
|
12 |
+
self.contexts = []
|
13 |
+
self.ids = []
|
14 |
+
|
15 |
+
def add_document(self, text):
|
16 |
+
sentences = text.split("\n")
|
17 |
+
clean_sentences = [s.strip() for s in sentences if s.strip()]
|
18 |
+
embeddings = self.encoder.encode(clean_sentences)
|
19 |
+
self.index.add(embeddings)
|
20 |
+
self.contexts.extend(clean_sentences)
|
21 |
+
|
22 |
+
def retrieve(self, query, top_k=3):
|
23 |
+
q_vec = self.encoder.encode([query])
|
24 |
+
D, I = self.index.search(q_vec, top_k)
|
25 |
+
return [self.contexts[i] for i in I[0]]
|
26 |
+
|
27 |
+
def extract_text_from_file(file_path):
|
28 |
+
ext = os.path.splitext(file_path)[-1].lower()
|
29 |
+
if ext == ".txt":
|
30 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
31 |
+
return f.read()
|
32 |
+
elif ext == ".pdf":
|
33 |
+
reader = PdfReader(file_path)
|
34 |
+
return "\n".join([page.extract_text() for page in reader.pages if page.extract_text()])
|
35 |
+
else:
|
36 |
+
return ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|