abdurrehmansaeed commited on
Commit
b878868
·
verified ·
1 Parent(s): b7b90b3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +125 -128
app.py CHANGED
@@ -1,129 +1,126 @@
1
- import os
2
- import tempfile
3
- import mimetypes
4
- from flask import Flask, request, jsonify
5
- from dotenv import load_dotenv
6
- from langchain_community.document_loaders import PyMuPDFLoader
7
- from langchain_text_splitters import RecursiveCharacterTextSplitter
8
- from langchain_huggingface import HuggingFaceEmbeddings
9
- from langchain_groq import ChatGroq
10
- from langchain_community.vectorstores import FAISS
11
- from langchain_classic.chains import create_retrieval_chain
12
- from langchain_classic.chains.combine_documents import create_stuff_documents_chain
13
- from langchain_core.prompts import ChatPromptTemplate
14
-
15
- # --- FORCE MIME TYPES FOR WINDOWS ---
16
- mimetypes.add_type('text/css', '.css')
17
- mimetypes.add_type('application/javascript', '.jsx')
18
-
19
-
20
- app = Flask(__name__, static_folder='frontend', static_url_path='/')
21
- global_vector_store = None
22
-
23
- # --- LLM ---
24
- load_dotenv()
25
- groq_api_key = os.getenv("GROQ_API_KEY")
26
-
27
- if not groq_api_key:
28
- raise ValueError("🚨 CRITICAL ERROR: Groq API Key not found. Ensure your .env contains GROQ_API_KEY=gsk_...")
29
-
30
- embeddings = HuggingFaceEmbeddings(model_name="BAAI/bge-small-en-v1.5")
31
- llm = ChatGroq(
32
- temperature=0.1,
33
- model_name="llama-3.3-70b-versatile",
34
- groq_api_key=groq_api_key
35
- )
36
-
37
- @app.route('/')
38
- def serve_index():
39
- return app.send_static_file('index.html')
40
-
41
- # --- UPLOAD & PROCESS PDF ---
42
- @app.route('/upload', methods=['POST'])
43
- def upload_file():
44
- global global_vector_store
45
-
46
- if 'file' not in request.files:
47
- return jsonify({"error": "No file part"}), 400
48
-
49
- file = request.files['file']
50
- if file.filename == '':
51
- return jsonify({"error": "No selected file"}), 400
52
-
53
- try:
54
- with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
55
- file.save(tmp_file.name)
56
- tmp_file_path = tmp_file.name
57
-
58
- loader = PyMuPDFLoader(tmp_file_path)
59
- documents = loader.load()
60
-
61
- text_splitter = RecursiveCharacterTextSplitter(
62
- separators=["\n\n", "\n", " ", ""],
63
- chunk_size=1000,
64
- chunk_overlap=200
65
- )
66
- chunks = text_splitter.split_documents(documents)
67
-
68
- global_vector_store = FAISS.from_documents(chunks, embeddings)
69
-
70
- intro_text = " ".join([doc.page_content for doc in chunks[:4]])
71
- extraction_prompt = f"""
72
- Based on the following introductory text from a research paper, provide:
73
- 1. A 2-sentence summary of the paper.
74
- 2. The core problem the authors are trying to solve.
75
- 3. The primary methodology or model architecture proposed.
76
-
77
- Text: {intro_text}
78
- """
79
-
80
- response = llm.invoke([("human", extraction_prompt)])
81
- os.remove(tmp_file_path)
82
-
83
- return jsonify({"insights": response.content}), 200
84
-
85
- except Exception as e:
86
- return jsonify({"error": str(e)}), 500
87
-
88
- # --- CHAT WITH PDF ---
89
- @app.route('/chat', methods=['POST'])
90
- def chat():
91
- global global_vector_store
92
-
93
- if not global_vector_store:
94
- return jsonify({"error": "Please upload a document first."}), 400
95
-
96
- data = request.json
97
- user_message = data.get('message')
98
-
99
- if not user_message:
100
- return jsonify({"error": "No message provided."}), 400
101
-
102
- try:
103
- retriever = global_vector_store.as_retriever(search_kwargs={"k": 4})
104
-
105
- system_prompt = (
106
- "You are a highly technical AI assistant helping a machine learning engineer understand a research paper. "
107
- "Use the following pieces of retrieved context to answer the question. "
108
- "If the answer is not in the context, state clearly that the paper does not mention it. "
109
- "Keep the answer concise and highly technical.\n\n"
110
- "Context: {context}"
111
- )
112
-
113
- prompt = ChatPromptTemplate.from_messages([
114
- ("system", system_prompt),
115
- ("human", "{input}"),
116
- ])
117
-
118
- question_answer_chain = create_stuff_documents_chain(llm, prompt)
119
- rag_chain = create_retrieval_chain(retriever, question_answer_chain)
120
-
121
- response = rag_chain.invoke({"input": user_message})
122
-
123
- return jsonify({"answer": response["answer"]}), 200
124
-
125
- except Exception as e:
126
- return jsonify({"error": str(e)}), 500
127
-
128
- if __name__ == '__main__':
129
  app.run(host='0.0.0.0', port=7860, debug=True)
 
1
+ import os
2
+ import tempfile
3
+ import mimetypes
4
+ from flask import Flask, request, jsonify
5
+ from dotenv import load_dotenv
6
+ from langchain_community.document_loaders import PyMuPDFLoader
7
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
8
+ from langchain_huggingface import HuggingFaceEmbeddings
9
+ from langchain_groq import ChatGroq
10
+ from langchain_community.vectorstores import FAISS
11
+ from langchain_classic.chains import create_retrieval_chain
12
+ from langchain_classic.chains.combine_documents import create_stuff_documents_chain
13
+ from langchain_core.prompts import ChatPromptTemplate
14
+
15
+ # --- FORCE MIME TYPES FOR WINDOWS ---
16
+ mimetypes.add_type('text/css', '.css')
17
+ mimetypes.add_type('application/javascript', '.jsx')
18
+
19
+
20
+ app = Flask(__name__, static_folder='frontend', static_url_path='/')
21
+ global_vector_store = None
22
+
23
+ # --- LLM ---
24
+ load_dotenv()
25
+ groq_api_key = os.getenv("GROQ_API_KEY")
26
+
27
+ embeddings = HuggingFaceEmbeddings(model_name="BAAI/bge-small-en-v1.5")
28
+ llm = ChatGroq(
29
+ temperature=0.1,
30
+ model_name="llama-3.3-70b-versatile",
31
+ groq_api_key=groq_api_key
32
+ )
33
+
34
+ @app.route('/')
35
+ def serve_index():
36
+ return app.send_static_file('index.html')
37
+
38
+ # --- UPLOAD & PROCESS PDF ---
39
+ @app.route('/upload', methods=['POST'])
40
+ def upload_file():
41
+ global global_vector_store
42
+
43
+ if 'file' not in request.files:
44
+ return jsonify({"error": "No file part"}), 400
45
+
46
+ file = request.files['file']
47
+ if file.filename == '':
48
+ return jsonify({"error": "No selected file"}), 400
49
+
50
+ try:
51
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
52
+ file.save(tmp_file.name)
53
+ tmp_file_path = tmp_file.name
54
+
55
+ loader = PyMuPDFLoader(tmp_file_path)
56
+ documents = loader.load()
57
+
58
+ text_splitter = RecursiveCharacterTextSplitter(
59
+ separators=["\n\n", "\n", " ", ""],
60
+ chunk_size=1000,
61
+ chunk_overlap=200
62
+ )
63
+ chunks = text_splitter.split_documents(documents)
64
+
65
+ global_vector_store = FAISS.from_documents(chunks, embeddings)
66
+
67
+ intro_text = " ".join([doc.page_content for doc in chunks[:4]])
68
+ extraction_prompt = f"""
69
+ Based on the following introductory text from a research paper, provide:
70
+ 1. A 2-sentence summary of the paper.
71
+ 2. The core problem the authors are trying to solve.
72
+ 3. The primary methodology or model architecture proposed.
73
+
74
+ Text: {intro_text}
75
+ """
76
+
77
+ response = llm.invoke([("human", extraction_prompt)])
78
+ os.remove(tmp_file_path)
79
+
80
+ return jsonify({"insights": response.content}), 200
81
+
82
+ except Exception as e:
83
+ return jsonify({"error": str(e)}), 500
84
+
85
+ # --- CHAT WITH PDF ---
86
+ @app.route('/chat', methods=['POST'])
87
+ def chat():
88
+ global global_vector_store
89
+
90
+ if not global_vector_store:
91
+ return jsonify({"error": "Please upload a document first."}), 400
92
+
93
+ data = request.json
94
+ user_message = data.get('message')
95
+
96
+ if not user_message:
97
+ return jsonify({"error": "No message provided."}), 400
98
+
99
+ try:
100
+ retriever = global_vector_store.as_retriever(search_kwargs={"k": 4})
101
+
102
+ system_prompt = (
103
+ "You are a highly technical AI assistant helping a machine learning engineer understand a research paper. "
104
+ "Use the following pieces of retrieved context to answer the question. "
105
+ "If the answer is not in the context, state clearly that the paper does not mention it. "
106
+ "Keep the answer concise and highly technical.\n\n"
107
+ "Context: {context}"
108
+ )
109
+
110
+ prompt = ChatPromptTemplate.from_messages([
111
+ ("system", system_prompt),
112
+ ("human", "{input}"),
113
+ ])
114
+
115
+ question_answer_chain = create_stuff_documents_chain(llm, prompt)
116
+ rag_chain = create_retrieval_chain(retriever, question_answer_chain)
117
+
118
+ response = rag_chain.invoke({"input": user_message})
119
+
120
+ return jsonify({"answer": response["answer"]}), 200
121
+
122
+ except Exception as e:
123
+ return jsonify({"error": str(e)}), 500
124
+
125
+ if __name__ == '__main__':
 
 
 
126
  app.run(host='0.0.0.0', port=7860, debug=True)