Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,107 +1,107 @@
|
|
1 |
-
import os
|
2 |
-
import logging
|
3 |
-
from dotenv import load_dotenv
|
4 |
-
from fastapi import FastAPI, Request, Form
|
5 |
-
from fastapi.responses import JSONResponse, HTMLResponse
|
6 |
-
from fastapi.middleware.cors import CORSMiddleware
|
7 |
-
from fastapi.templating import Jinja2Templates
|
8 |
-
from
|
9 |
-
from
|
10 |
-
from langchain.chains import LLMChain
|
11 |
-
from langchain.prompts import PromptTemplate
|
12 |
-
from
|
13 |
-
|
14 |
-
# Load environment variables
|
15 |
-
load_dotenv()
|
16 |
-
|
17 |
-
# Securely retrieve the OpenAI API key
|
18 |
-
openai_api_key = os.getenv("sk-89la-SEB-GWL62eQC0RYXpVzPlYGLCZuXIAz39F58YT3BlbkFJqdiuuTxIAUwxud-MhcL6tAjLxZJvXbpEEcMUkN8DIA")
|
19 |
-
if not openai_api_key:
|
20 |
-
raise ValueError("Missing OpenAI API key. Set OPENAI_API_KEY in your environment variables.")
|
21 |
-
|
22 |
-
# Initialize FastAPI app
|
23 |
-
app = FastAPI()
|
24 |
-
templates = Jinja2Templates(directory="templates")
|
25 |
-
|
26 |
-
# Configure CORS
|
27 |
-
app.add_middleware(
|
28 |
-
CORSMiddleware,
|
29 |
-
allow_origins=["*"],
|
30 |
-
allow_credentials=True,
|
31 |
-
allow_methods=["*"],
|
32 |
-
allow_headers=["*"],
|
33 |
-
)
|
34 |
-
|
35 |
-
# Configure logging
|
36 |
-
logging.basicConfig(level=logging.INFO)
|
37 |
-
logger = logging.getLogger(__name__)
|
38 |
-
|
39 |
-
# Initialize OpenAI embeddings
|
40 |
-
embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key)
|
41 |
-
|
42 |
-
# Load FAISS index with error handling
|
43 |
-
try:
|
44 |
-
db = FAISS.load_local("faiss_index", embeddings)
|
45 |
-
logger.info("FAISS index loaded successfully.")
|
46 |
-
except Exception as e:
|
47 |
-
logger.error(f"Error loading FAISS index: {e}")
|
48 |
-
db = None # Avoid crashing
|
49 |
-
|
50 |
-
# Define the prompt template
|
51 |
-
prompt_template = """
|
52 |
-
You are an expert in skin cancer research.
|
53 |
-
Answer the question based only on the provided context, which may include text, images, or tables.
|
54 |
-
|
55 |
-
Context:
|
56 |
-
{context}
|
57 |
-
|
58 |
-
Question: {question}
|
59 |
-
|
60 |
-
If the context does not contain sufficient information, say: "Sorry, I don't have much information about it."
|
61 |
-
|
62 |
-
Answer:
|
63 |
-
"""
|
64 |
-
|
65 |
-
qa_chain = LLMChain(
|
66 |
-
llm=ChatOpenAI(model="gpt-4", openai_api_key=openai_api_key, max_tokens=1024),
|
67 |
-
prompt=PromptTemplate.from_template(prompt_template),
|
68 |
-
)
|
69 |
-
|
70 |
-
@app.get("/", response_class=HTMLResponse)
|
71 |
-
async def index(request: Request):
|
72 |
-
return templates.TemplateResponse("index.html", {"request": request})
|
73 |
-
|
74 |
-
@app.post("/get_answer")
|
75 |
-
async def get_answer(question: str = Form(...)):
|
76 |
-
if db is None:
|
77 |
-
return JSONResponse({"error": "FAISS database is unavailable."}, status_code=500)
|
78 |
-
|
79 |
-
try:
|
80 |
-
# Retrieve relevant documents from FAISS
|
81 |
-
relevant_docs = db.similarity_search(question)
|
82 |
-
context = ""
|
83 |
-
relevant_images = []
|
84 |
-
|
85 |
-
for d in relevant_docs:
|
86 |
-
doc_type = d.metadata.get('type', 'text')
|
87 |
-
original_content = d.metadata.get('original_content', '')
|
88 |
-
|
89 |
-
if doc_type == 'text':
|
90 |
-
context += f"[text] {original_content}\n"
|
91 |
-
elif doc_type == 'table':
|
92 |
-
context += f"[table] {original_content}\n"
|
93 |
-
elif doc_type == 'image':
|
94 |
-
context += f"[image] {d.page_content}\n"
|
95 |
-
relevant_images.append(original_content)
|
96 |
-
|
97 |
-
# Run the question-answering chain
|
98 |
-
result = qa_chain.run({'context': context, 'question': question})
|
99 |
-
|
100 |
-
# Handle cases where no relevant images are found
|
101 |
-
return JSONResponse({
|
102 |
-
"relevant_images": relevant_images[0] if relevant_images else None,
|
103 |
-
"result": result,
|
104 |
-
})
|
105 |
-
except Exception as e:
|
106 |
-
logger.error(f"Error processing request: {e}")
|
107 |
-
return JSONResponse({"error": "Internal server error."}, status_code=500)
|
|
|
1 |
+
import os
|
2 |
+
import logging
|
3 |
+
from dotenv import load_dotenv
|
4 |
+
from fastapi import FastAPI, Request, Form
|
5 |
+
from fastapi.responses import JSONResponse, HTMLResponse
|
6 |
+
from fastapi.middleware.cors import CORSMiddleware
|
7 |
+
from fastapi.templating import Jinja2Templates
|
8 |
+
from langchain_community.chat_models import ChatOpenAI
|
9 |
+
from langchain_community.embeddings import OpenAIEmbeddings
|
10 |
+
from langchain.chains import LLMChain
|
11 |
+
from langchain.prompts import PromptTemplate
|
12 |
+
from langchain_community.vectorstores import FAISS
|
13 |
+
|
14 |
+
# Load environment variables
|
15 |
+
load_dotenv()
|
16 |
+
|
17 |
+
# Securely retrieve the OpenAI API key
|
18 |
+
openai_api_key = os.getenv("sk-89la-SEB-GWL62eQC0RYXpVzPlYGLCZuXIAz39F58YT3BlbkFJqdiuuTxIAUwxud-MhcL6tAjLxZJvXbpEEcMUkN8DIA")
|
19 |
+
if not openai_api_key:
|
20 |
+
raise ValueError("Missing OpenAI API key. Set OPENAI_API_KEY in your environment variables.")
|
21 |
+
|
22 |
+
# Initialize FastAPI app
|
23 |
+
app = FastAPI()
|
24 |
+
templates = Jinja2Templates(directory="templates")
|
25 |
+
|
26 |
+
# Configure CORS
|
27 |
+
app.add_middleware(
|
28 |
+
CORSMiddleware,
|
29 |
+
allow_origins=["*"],
|
30 |
+
allow_credentials=True,
|
31 |
+
allow_methods=["*"],
|
32 |
+
allow_headers=["*"],
|
33 |
+
)
|
34 |
+
|
35 |
+
# Configure logging
|
36 |
+
logging.basicConfig(level=logging.INFO)
|
37 |
+
logger = logging.getLogger(__name__)
|
38 |
+
|
39 |
+
# Initialize OpenAI embeddings
|
40 |
+
embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key)
|
41 |
+
|
42 |
+
# Load FAISS index with error handling
|
43 |
+
try:
|
44 |
+
db = FAISS.load_local("faiss_index", embeddings)
|
45 |
+
logger.info("FAISS index loaded successfully.")
|
46 |
+
except Exception as e:
|
47 |
+
logger.error(f"Error loading FAISS index: {e}")
|
48 |
+
db = None # Avoid crashing
|
49 |
+
|
50 |
+
# Define the prompt template
|
51 |
+
prompt_template = """
|
52 |
+
You are an expert in skin cancer research.
|
53 |
+
Answer the question based only on the provided context, which may include text, images, or tables.
|
54 |
+
|
55 |
+
Context:
|
56 |
+
{context}
|
57 |
+
|
58 |
+
Question: {question}
|
59 |
+
|
60 |
+
If the context does not contain sufficient information, say: "Sorry, I don't have much information about it."
|
61 |
+
|
62 |
+
Answer:
|
63 |
+
"""
|
64 |
+
|
65 |
+
qa_chain = LLMChain(
|
66 |
+
llm=ChatOpenAI(model="gpt-4", openai_api_key=openai_api_key, max_tokens=1024),
|
67 |
+
prompt=PromptTemplate.from_template(prompt_template),
|
68 |
+
)
|
69 |
+
|
70 |
+
@app.get("/", response_class=HTMLResponse)
|
71 |
+
async def index(request: Request):
|
72 |
+
return templates.TemplateResponse("index.html", {"request": request})
|
73 |
+
|
74 |
+
@app.post("/get_answer")
|
75 |
+
async def get_answer(question: str = Form(...)):
|
76 |
+
if db is None:
|
77 |
+
return JSONResponse({"error": "FAISS database is unavailable."}, status_code=500)
|
78 |
+
|
79 |
+
try:
|
80 |
+
# Retrieve relevant documents from FAISS
|
81 |
+
relevant_docs = db.similarity_search(question)
|
82 |
+
context = ""
|
83 |
+
relevant_images = []
|
84 |
+
|
85 |
+
for d in relevant_docs:
|
86 |
+
doc_type = d.metadata.get('type', 'text')
|
87 |
+
original_content = d.metadata.get('original_content', '')
|
88 |
+
|
89 |
+
if doc_type == 'text':
|
90 |
+
context += f"[text] {original_content}\n"
|
91 |
+
elif doc_type == 'table':
|
92 |
+
context += f"[table] {original_content}\n"
|
93 |
+
elif doc_type == 'image':
|
94 |
+
context += f"[image] {d.page_content}\n"
|
95 |
+
relevant_images.append(original_content)
|
96 |
+
|
97 |
+
# Run the question-answering chain
|
98 |
+
result = qa_chain.run({'context': context, 'question': question})
|
99 |
+
|
100 |
+
# Handle cases where no relevant images are found
|
101 |
+
return JSONResponse({
|
102 |
+
"relevant_images": relevant_images[0] if relevant_images else None,
|
103 |
+
"result": result,
|
104 |
+
})
|
105 |
+
except Exception as e:
|
106 |
+
logger.error(f"Error processing request: {e}")
|
107 |
+
return JSONResponse({"error": "Internal server error."}, status_code=500)
|