File size: 4,814 Bytes
60d3c71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import datetime
import pickle
import typing
#19bc8e
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import ORJSONResponse, StreamingResponse
import ollama
from fastapi.staticfiles import StaticFiles
# uvicorn api:app --host 0.0.0.0 --port 8080  {text.replace(/<think>[\s\S]*?<\/think>/g, "") }
#https://arxiv.org/pdf/2202.04850v1

app = FastAPI(
    description="Knowledge graph.",
    title="FactGPT",
    version="0.0.1",
)

origins = [
    "http://localhost:8080",
]


app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],#origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


class Knowledge:
    """This class is a wrapper around the pipeline."""

    def __init__(self) -> None:
        self.pipeline = None

    def start(self):
        """Load the pipeline."""
        import os

        # Step 1: Change to the subfolder
        #os.chdir("knowledge")  # replace "folder" with your subfolder name
        print("Current directory (inside folder):", os.getcwd())

         #"database/pipeline.pkl" data/pipeline.pkl
        with open("data/pipeline.pkl", "rb") as f:
            self.pipeline = pickle.load(f)
        # Step 2: Go back to the parent directory
        #os.chdir("..")
        print("Current directory (after cd ..):", os.getcwd())
        return self

    def search(
        self,
        q: str,
        tags: str,
    ) -> typing.Dict:
        """Returns the documents."""
        return self.pipeline.search(q=q, tags=tags)

    def plot(
        self,
        q: str,
        k_tags: int,
        k_yens: int = 1,
        k_walk: int = 3,
    ) -> typing.Dict:
        """Returns the graph."""
        nodes, links = self.pipeline.plot(
            q=q,
            k_tags=k_tags,
            k_yens=k_yens,
            k_walk=k_walk,
        )
        return {"nodes": nodes, "links": links}


knowledge = Knowledge()




async def async_chat(query: str, content: str):
    """Re-rank the documents using a local Ollama model."""



    full_prompt = f"""
    You are a senior patent-search analyst.

    <task>
    - Restate the claim in one sentence.
    - For each paper, list its title, classify as:
    • Matched – fully covers all claim elements  
    • Similar   – covers most elements or if any doubt  
    • Irrelevant – no meaningful overlap  
    then give a 1–2 sentence rationale.
    </task>

    <rules>
    • Rely only on the provided text.  
    • If in doubt, classify as Similar.  
    • Do not invent content.
    </rules>

    <claim>
    {query}
    </claim>

    <papers>
    {content}
    </papers>
    """

    response = ollama.chat(
        model="qwen3:1.7b",  # or "llama3", "mistral", etc.
        messages=[{"role": "user", "content": full_prompt}],
        stream=True, options={'temperature': .5},
    )

    answer = "\n"
    for chunk in response:
        token = chunk["message"]["content"]
        answer += token
        #answer = answer
        yield answer.strip()


@app.get("/search/{sort}/{tags}/{k_tags}/{q}")
def search(k_tags: int, tags: str, sort: bool, q: str):
    """Search for documents."""
    tags = tags != "null"#tags = tags.lower() != "false" and tags.lower() != "null"#
    documents = knowledge.search(q=q, tags=tags)
    if bool(sort):
        documents = [
            document
            for _, document in sorted(
                [(document["date"], document) for document in documents],
                key=lambda document: datetime.datetime.strptime(
                    document[0], "%Y-%m-%d"
                ),
                reverse=True,
            )
        ]
    return {"documents": documents}


@app.get("/plot/{k_tags}/{q}", response_class=ORJSONResponse)
def plot(k_tags: int, q: str):
    """Plot tags."""
    return knowledge.plot(q=q, k_tags=k_tags)


@app.on_event("startup")
def start():
    """Intialiaze the pipeline."""
    return knowledge.start()


@app.get("/chat/{k_tags}/{q}")
async def chat(k_tags: int, q: str):
    """LLM recommendation."""
    documents = knowledge.search(q=q, tags=False)
    content = ""
    count=0
    for document in documents:
        count+=1
        content += f"TITLE: {count}" + document["title"] + "\n"
        content += "summary: " + document["summary"][:30] + "\n"
        content += "targs: " + (
            ", ".join(document["tags"] + document["extra-tags"]) + "\n"
        )
        #content += "url: " + document["url"] + "\n\n"
        content +='\n\n\n'
        if count>10:break
    #content = "title: ".join(content[:3000].split("title:")[:-1])
    return StreamingResponse(
        async_chat(query=q, content=content), media_type="text/plain"
    )


app.mount("/", StaticFiles(directory="docs", html=True), name="static")