schmidj commited on
Commit
14c2543
·
verified ·
1 Parent(s): 387d82b

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +145 -0
  2. retrieval_engine.py +255 -0
  3. templates/index.html +128 -0
app.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, request, redirect, url_for, flash
2
+ import os
3
+ #import pymupdf4llm
4
+ import fitz
5
+ import requests
6
+ import json
7
+ import logging
8
+ from dotenv import load_dotenv
9
+ from retrieval_engine import HybridRetriever
10
+
11
+ # --- Setup ---
12
+ logging.basicConfig(level=logging.INFO)
13
+ logger = logging.getLogger(__name__)
14
+
15
+ app = Flask(__name__)
16
+ app.secret_key = "dev-secret-key"
17
+ load_dotenv()
18
+
19
+ TOGETHER_API_KEY = os.getenv("TOGETHER_API_KEY")
20
+ TOGETHER_API_URL = "https://api.together.xyz/v1/chat/completions"
21
+ LLM_MODEL = "meta-llama/Llama-3.3-70B-Instruct-Turbo-Free"
22
+
23
+
24
+ # --- PDF text extraction ---
25
+ def extract_text_from_pdf(pdf_path):
26
+ doc = fitz.open(pdf_path)
27
+ text = []
28
+ for page_num, page in enumerate(doc, 1):
29
+ page_text = page.get_text()
30
+ text.append(page_text)
31
+ return '\n'.join(text)
32
+
33
+
34
+ # --- Metadata extraction ---
35
+ def extract_metadata_from_pdf(pdf_text, retriever):
36
+ """
37
+ Use FAISS+BM25 retriever and Together.ai LLM to extract structured metadata.
38
+ """
39
+ # Step 1: Split PDF text into chunks
40
+ chunks = [pdf_text[i:i+2000] for i in range(0, len(pdf_text), 2000)]
41
+ retriever.fit(chunks)
42
+
43
+ # Step 2: Query the retriever
44
+ query = "Extract metadata from this research paper including title, authors, abstract, methods, datasets, and findings."
45
+ retrieved_docs = retriever.retrieve(query, top_k=5)
46
+
47
+ # Step 3: Build LLM prompt
48
+ context = "\n\n".join(retrieved_docs)
49
+ prompt = f"""
50
+ Extract the following metadata from the research paper text below:
51
+ - Title
52
+ - Authors
53
+ - Publication date
54
+ - Journal/venue
55
+ - DOI
56
+ - Abstract
57
+ - Keywords
58
+ - Study methods
59
+ - Datasets used
60
+ - Geographic and temporal coverage
61
+ - Sample size
62
+ - Key findings
63
+ Extract the list of author names only, without affiliations or emails.
64
+
65
+
66
+ Return as structured JSON.
67
+ Text:
68
+ {context}
69
+ """
70
+
71
+ # Step 4: Call Together.ai LLM
72
+ headers = {
73
+ "Authorization": f"Bearer {TOGETHER_API_KEY}",
74
+ "Content-Type": "application/json"
75
+ }
76
+
77
+ data = {
78
+ "model": LLM_MODEL,
79
+ "messages": [{"role": "user", "content": prompt}],
80
+ "max_tokens": 2000,
81
+ "temperature": 0.1
82
+ }
83
+
84
+ try:
85
+ response = requests.post(TOGETHER_API_URL, headers=headers, json=data)
86
+ response.raise_for_status()
87
+ content = response.json()["choices"][0]["message"]["content"]
88
+
89
+ # Clean markdown formatting
90
+ content = content.strip()
91
+ if "```" in content:
92
+ # Extract inside the first code block
93
+ parts = content.split("```")
94
+ if len(parts) >= 2:
95
+ content = parts[1]
96
+ content = content.replace("json", "", 1).strip()
97
+
98
+ # Try loading JSON
99
+ metadata = json.loads(content)
100
+ return metadata
101
+
102
+ except json.JSONDecodeError as e:
103
+ logger.error(f"JSON decoding failed: {e}")
104
+ logger.error(f"Content was:\n{content[:500]}")
105
+ return {"error": f"JSON decoding failed: {str(e)}", "raw_response": content}
106
+
107
+ except Exception as e:
108
+ logger.error(f"Error calling Together.ai API: {e}")
109
+ return {"error": str(e), "raw_response": content if 'content' in locals() else None}
110
+
111
+
112
+ # --- Flask routes ---
113
+ @app.route("/", methods=["GET"])
114
+ def index():
115
+ return render_template("index.html", metadata=None)
116
+
117
+
118
+ @app.route("/process", methods=["POST"])
119
+ def process():
120
+ uploaded_file = request.files.get("pdf_file")
121
+
122
+ if not uploaded_file or uploaded_file.filename == "":
123
+ flash("Please upload a PDF.")
124
+ return redirect(url_for("index"))
125
+
126
+ uploads_dir = os.path.join(os.getcwd(), "uploads")
127
+ os.makedirs(uploads_dir, exist_ok=True)
128
+ pdf_path = os.path.join(uploads_dir, uploaded_file.filename)
129
+ uploaded_file.save(pdf_path)
130
+
131
+ logger.info(f"Processing PDF: {pdf_path}")
132
+
133
+ pdf_text = extract_text_from_pdf(pdf_path)
134
+ if not pdf_text:
135
+ flash("Error extracting text from PDF.")
136
+ return redirect(url_for("index"))
137
+
138
+ retriever = HybridRetriever()
139
+ metadata = extract_metadata_from_pdf(pdf_text, retriever)
140
+
141
+ return render_template("index.html", metadata=metadata)
142
+
143
+
144
+ if __name__ == "__main__":
145
+ app.run(debug=True)
retrieval_engine.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import numpy as np
4
+ import pickle
5
+ import time
6
+ from typing import List, Dict, Any, Tuple
7
+ from pathlib import Path
8
+ from dotenv import load_dotenv
9
+ import faiss
10
+ from rank_bm25 import BM25Okapi
11
+ from sentence_transformers import CrossEncoder
12
+ import torch
13
+ from openai import OpenAI
14
+
15
+ # Load environment variables for API keys
16
+ load_dotenv()
17
+
18
+ # Initialize OpenAI client
19
+ client = OpenAI(api_key=os.environ.get('OPENAI_API_KEY'))
20
+
21
+ # Define paths
22
+ BASE_DIR = Path(os.path.dirname(os.path.abspath(__file__)))
23
+ INDEX_DIR = BASE_DIR / 'index'
24
+ os.makedirs(INDEX_DIR, exist_ok=True)
25
+
26
+ # Define file paths
27
+ VECTORS_FILE = INDEX_DIR / 'vectors.faiss'
28
+ BM25_FILE = INDEX_DIR / 'bm25_index.pkl'
29
+ CHUNKS_FILE = INDEX_DIR / 'chunks.json' #This cames from the first step
30
+ RAG_CHUNKS_FILE = BASE_DIR / 'rag_ingested_chunks.json' #at the end is my chunks.json
31
+
32
+ # Initialize cross-encoder for reranking
33
+ cross_encoder = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')
34
+
35
+
36
+ #IM not using this fucntion because I've replaced for IndexFlatIP # Create FAISS index
37
+ #def cosine_similarity(a, b):
38
+ #Calculate cosine similarity between two vectors
39
+ # return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
40
+
41
+
42
+ def reciprocal_rank_fusion(rank_lists, k=60):
43
+ """
44
+ Implement Reciprocal Rank Fusion to combine multiple ranked lists
45
+
46
+ Args:
47
+ rank_lists: List of lists, each inner list contains dicts with 'id', 'text', and other metadata
48
+ k: Constant in RRF formula, typically set to 60
49
+
50
+ Returns:
51
+ List of dicts with combined RRF scores
52
+ """
53
+ from collections import defaultdict
54
+
55
+ # Track all unique chunks across all lists
56
+ all_chunks = {}
57
+ chunk_to_ranks = defaultdict(list)
58
+
59
+ # Process each ranked list
60
+ for rank_list in rank_lists:
61
+ for rank, chunk in enumerate(rank_list):
62
+ chunk_id = chunk['id']
63
+ # Store the chunk data if we haven't seen it yet
64
+ if chunk_id not in all_chunks:
65
+ all_chunks[chunk_id] = chunk
66
+ # Store the rank from this list
67
+ chunk_to_ranks[chunk_id].append(rank + 1) # +1 because RRF uses 1-based ranks
68
+
69
+ # Calculate RRF scores for each chunk
70
+ rrf_scores = {}
71
+ for chunk_id, ranks in chunk_to_ranks.items():
72
+ # For each chunk, calculate the RRF score across all lists
73
+ rrf_score = sum(1.0 / (k + r) for r in ranks)
74
+ rrf_scores[chunk_id] = rrf_score
75
+
76
+ # Create the final combined list
77
+ combined_results = []
78
+ for chunk_id, score in sorted(rrf_scores.items(), key=lambda x: x[1], reverse=True):
79
+ result = all_chunks[chunk_id].copy()
80
+ result['rrf_score'] = score
81
+ combined_results.append(result)
82
+
83
+ return combined_results
84
+
85
+
86
+ def rerank_with_cross_encoder(query, results, top_k=10):
87
+ """
88
+ Rerank results using a cross-encoder model
89
+
90
+ Args:
91
+ query: The user query
92
+ results: List of result dicts with 'id' and 'text' fields
93
+ top_k: Number of top results to return after reranking
94
+
95
+ Returns:
96
+ Reranked list of results
97
+ """
98
+ if not results:
99
+ return []
100
+
101
+ # Prepare pairs for the cross-encoder
102
+ pairs = [(query, result['text']) for result in results]
103
+
104
+ # Get scores from the cross-encoder
105
+ scores = cross_encoder.predict(pairs)
106
+
107
+ # Add scores to results
108
+ for i, result in enumerate(results):
109
+ result['cross_encoder_score'] = float(scores[i])
110
+
111
+ # Sort by cross-encoder score
112
+ reranked_results = sorted(results, key=lambda x: x['cross_encoder_score'], reverse=True)
113
+
114
+ # Return top-k results
115
+ return reranked_results[:top_k]
116
+
117
+
118
+ def format_context(results, max_tokens=3000):
119
+ """
120
+ Format the retrieved chunks into a context string for the LLM
121
+
122
+ Args:
123
+ results: List of result dicts with 'id' and 'text' fields
124
+ max_tokens: Maximum number of tokens to include in the context
125
+
126
+ Returns:
127
+ Formatted context string
128
+ """
129
+ context_parts = []
130
+ current_tokens = 0
131
+
132
+ for result in results:
133
+ # Format: "<id>: <text>"
134
+ chunk_text = f"{result['id']}: {result['text']}"
135
+ # Approximate token count (4 chars ~= 1 token)
136
+ chunk_tokens = len(chunk_text) // 4
137
+
138
+ if current_tokens + chunk_tokens > max_tokens:
139
+ break
140
+
141
+ context_parts.append(chunk_text)
142
+ current_tokens += chunk_tokens
143
+
144
+ return "\n\n---\n\n".join(context_parts)
145
+
146
+
147
+ def tokenize_text(text):
148
+ """Simple tokenization for BM25"""
149
+ return text.lower().split()
150
+
151
+
152
+ def create_vector_index(chunks):
153
+ """Create a FAISS index from chunk embeddings"""
154
+ # Extract embeddings from chunks
155
+ embeddings = [chunk['embedding'] for chunk in chunks]
156
+
157
+ # Convert to numpy array
158
+ embeddings_array = np.array(embeddings).astype('float32')
159
+
160
+ # Get dimensionality of embeddings
161
+ dimension = embeddings_array.shape[1]
162
+
163
+ # Create FAISS index
164
+ index = faiss.IndexFlatIP(dimension) # Inner product (cosine similarity for normalized vectors)
165
+ index.add(embeddings_array)
166
+
167
+ return index
168
+
169
+
170
+ def create_bm25_index(chunks):
171
+ """Create a BM25 index from chunk texts"""
172
+ # Extract texts from chunks
173
+ texts = [chunk['text'] for chunk in chunks]
174
+
175
+ # Tokenize texts
176
+ tokenized_texts = [tokenize_text(text) for text in texts]
177
+
178
+ # Create BM25 index
179
+ bm25_index = BM25Okapi(tokenized_texts)
180
+
181
+ return bm25_index
182
+
183
+
184
+ def main():
185
+ """
186
+ Main function to load chunks, create indices, and demonstrate retrieval
187
+ """
188
+ print("Loading chunks from rag_ingested_chunks.json...")
189
+
190
+ # Load chunks from file
191
+ try:
192
+ with open(RAG_CHUNKS_FILE, 'r', encoding='utf-8') as f:
193
+ chunks = json.load(f)
194
+ print(f"Loaded {len(chunks)} chunks")
195
+ except Exception as e:
196
+ print(f"Error loading chunks: {e}")
197
+ return
198
+
199
+ # Create vector index
200
+ print("Creating vector index...")
201
+ vector_index = create_vector_index(chunks)
202
+
203
+ # Create BM25 index
204
+ print("Creating BM25 index...")
205
+ bm25_index = create_bm25_index(chunks)
206
+
207
+ # Save indices
208
+ print("Saving indices...")
209
+ faiss.write_index(vector_index, str(VECTORS_FILE))
210
+ with open(BM25_FILE, 'wb') as f:
211
+ pickle.dump(bm25_index, f)
212
+
213
+ # Save chunks to index directory for the chat application
214
+ with open(CHUNKS_FILE, 'w', encoding='utf-8') as f:
215
+ json.dump(chunks, f, indent=2)
216
+
217
+ print(f"Indices and chunks saved to {INDEX_DIR}")
218
+ print("Processing complete. You can now run the chat application (3new_chat.py).")
219
+
220
+
221
+ class HybridRetriever:
222
+ def __init__(self):
223
+ self.vector_index = None
224
+ self.bm25_index = None
225
+ self.chunks = []
226
+
227
+ def fit(self, chunks):
228
+ """Fit the retriever with text chunks"""
229
+ # Simple chunking - you might want to add embeddings here
230
+ self.chunks = [{"id": i, "text": chunk} for i, chunk in enumerate(chunks)]
231
+
232
+ # Create BM25 index
233
+ texts = [chunk["text"] for chunk in self.chunks]
234
+ tokenized_texts = [tokenize_text(text) for text in texts]
235
+ self.bm25_index = BM25Okapi(tokenized_texts)
236
+
237
+ def retrieve(self, query, top_k=5):
238
+ """Retrieve relevant chunks using BM25"""
239
+ if not self.bm25_index:
240
+ return []
241
+
242
+ # Tokenize query
243
+ query_tokens = tokenize_text(query)
244
+
245
+ # Get BM25 scores
246
+ scores = self.bm25_index.get_scores(query_tokens)
247
+
248
+ # Get top-k results
249
+ top_indices = np.argsort(scores)[-top_k:][::-1]
250
+
251
+ return [self.chunks[i]["text"] for i in top_indices]
252
+
253
+
254
+ if __name__ == "__main__":
255
+ main()
templates/index.html ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>MetaFinder - Metadata Extractor</title>
7
+ <style>
8
+ body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif; margin: 0; background: #f6f7f9; color: #111; }
9
+ .container { max-width: 720px; margin: 40px auto; background: #fff; border: 1px solid #e5e7eb; border-radius: 12px; padding: 24px; box-shadow: 0 2px 6px rgba(0,0,0,0.04); }
10
+ h1 { font-size: 22px; margin: 0 0 16px; }
11
+ p.hint { color: #555; margin: 0 0 16px; }
12
+ form { display: grid; gap: 12px; margin-top: 8px; }
13
+ .field { display: grid; gap: 6px; }
14
+ label { font-weight: 600; font-size: 14px; }
15
+ input[type="text"], input[type="file"] { padding: 10px 12px; border: 1px solid #d1d5db; border-radius: 8px; font-size: 14px; background: #fff; }
16
+ .or { text-align: center; color: #6b7280; font-size: 12px; margin: 4px 0; }
17
+ .actions { display: flex; gap: 8px; margin-top: 8px; }
18
+ button { cursor: pointer; border: 0; padding: 10px 14px; border-radius: 8px; font-weight: 600; font-size: 14px; }
19
+ .primary { background: #111827; color: #fff; }
20
+ .secondary { background: #e5e7eb; color: #111; }
21
+ .card { border: 1px solid #e5e7eb; border-radius: 10px; padding: 16px; background: #fafafa; }
22
+ .kv { display: grid; grid-template-columns: 160px 1fr; gap: 8px 12px; }
23
+ .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 13px; }
24
+ .muted { color: #6b7280; }
25
+ .row-list { display: grid; gap: 6px; }
26
+ .download { margin-top: 12px; }
27
+ .flash { background: #fff7ed; border: 1px solid #fed7aa; padding: 10px 12px; border-radius: 8px; color: #9a3412; margin-bottom: 12px; }
28
+ </style>
29
+ </head>
30
+ <body>
31
+ <div class="container">
32
+ <h1>MetaFinder AI</h1>
33
+ <p class="hint">Upload a PDF or enter a DOI. Click Generate to see a summary.</p>
34
+
35
+ {% with messages = get_flashed_messages() %}
36
+ {% if messages %}
37
+ <div class="flash">{{ messages[0] }}</div>
38
+ {% endif %}
39
+ {% endwith %}
40
+
41
+ <form action="{{ url_for('process') }}" method="post" enctype="multipart/form-data">
42
+ <div class="field">
43
+ <label for="pdf_file">PDF file</label>
44
+ <input id="pdf_file" name="pdf_file" type="file" accept="application/pdf">
45
+ </div>
46
+
47
+ <div class="or">— or —</div>
48
+
49
+ <div class="field">
50
+ <label for="doi">DOI</label>
51
+ <input id="doi" name="doi" type="text" placeholder="10.xxxx/xxxxxx">
52
+ </div>
53
+
54
+ <div class="actions">
55
+ <button class="primary" type="submit">Generate</button>
56
+ {% if metadata %}
57
+ <button class="secondary" type="button" id="downloadJson">Download JSON</button>
58
+ <a class="secondary" href="{{ url_for('index') }}" style="text-decoration:none; display:inline-block; padding:10px 14px; border-radius:8px;">Reset</a>
59
+ {% endif %}
60
+ </div>
61
+ </form>
62
+
63
+ {% if metadata %}
64
+ <div class="card" style="margin-top:16px;">
65
+ <h2 style="margin:0 0 8px; font-size:18px;">Summary</h2>
66
+
67
+ <!-- Display all metadata fields dynamically -->
68
+ <div class="kv">
69
+ {% for key, value in metadata.items() %}
70
+ {% if value is not none and value != "" and value != [] and value != {} %}
71
+ <div class="muted">{{ key.replace('_', ' ').title() }}</div>
72
+ <div>
73
+ {% if value is mapping %}
74
+ <!-- Handle nested objects -->
75
+ <div class="mono">{{ value | tojson(indent=2) }}</div>
76
+ {% elif value is iterable and value is not string %}
77
+ <!-- Handle lists -->
78
+ {% if value | length > 0 %}
79
+ <div>- {{ value | join('\n- ') | replace('\n', '<br>') | safe }}</div>
80
+ {% else %}
81
+ <div class="muted">None</div>
82
+ {% endif %}
83
+ {% else %}
84
+ <!-- Handle strings and other values -->
85
+ {% if value is string and value | length > 100 %}
86
+ <div class="mono" style="white-space:pre-wrap; max-height:120px; overflow:auto;">{{ value }}</div>
87
+ {% else %}
88
+ <div>{{ value }}</div>
89
+ {% endif %}
90
+ {% endif %}
91
+ </div>
92
+ {% endif %}
93
+ {% endfor %}
94
+ </div>
95
+
96
+ <div class="download">
97
+ <h3 style="margin:12px 0 8px; font-size:14px; color:#6b7280;">Raw JSON Data</h3>
98
+ <pre class="mono" id="jsonPreview" style="white-space:pre-wrap; background:#fff; border:1px solid #e5e7eb; border-radius:8px; padding:12px; max-height:240px; overflow:auto;">{{ metadata | tojson(indent=2) }}</pre>
99
+ </div>
100
+ </div>
101
+ {% endif %}
102
+ </div>
103
+
104
+ {% if metadata %}
105
+ <script>
106
+ (function() {
107
+ const data = {{ metadata | tojson }};
108
+ const btn = document.getElementById('downloadJson');
109
+ if (btn) {
110
+ btn.addEventListener('click', function() {
111
+ const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
112
+ const url = URL.createObjectURL(blob);
113
+ const a = document.createElement('a');
114
+ a.href = url;
115
+ a.download = 'metadata.json';
116
+ document.body.appendChild(a);
117
+ a.click();
118
+ a.remove();
119
+ URL.revokeObjectURL(url);
120
+ });
121
+ }
122
+ })();
123
+ </script>
124
+ {% endif %}
125
+ </body>
126
+ </html>
127
+
128
+