-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat.py
More file actions
95 lines (62 loc) · 1.48 KB
/
Copy pathchat.py
File metadata and controls
95 lines (62 loc) · 1.48 KB
1
2
3
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
from pathlib import Path
from pypdf import PdfReader
from ollama import chat
documents = {}
docs_folder = Path("docs")
# Load all documents
for file in docs_folder.iterdir():
content = ""
if file.suffix.lower() == ".pdf":
reader = PdfReader(file)
for page in reader.pages:
text = page.extract_text()
if text:
content += text + "\n"
elif file.suffix.lower() == ".txt":
with open(file, "r", encoding="utf-8") as f:
content = f.read()
documents[file.name] = content
question = input("Ask a question: ")
# Basic retrieval
best_doc = None
best_score = 0
question_words = question.lower().split()
for filename, content in documents.items():
score = 0
content_lower = content.lower()
for word in question_words:
if word in content_lower:
score += 1
if score > best_score:
best_score = score
best_doc = filename
if best_doc:
print(f"\nUsing document: {best_doc}")
prompt = f"""
Use the following document to answer the question.
DOCUMENT NAME:
{best_doc}
DOCUMENT:
{documents[best_doc][:5000]}
QUESTION:
{question}
"""
else:
prompt = f"""
Answer the question as best you can.
QUESTION:
{question}
"""
response = chat(
model="qwen3",
messages=[
{
"role": "user",
"content": prompt
}
]
)
print("\nAnswer:")
print(response.message.content)
if best_doc:
print(f"\nSource: {best_doc}")