chiluka commited on
Commit
fc53c09
·
1 Parent(s): 2f464e0

Fix citation extraction using Gemini and updated regex split fallback

Browse files
AI_Research_Assistant-backend/app/services/citation_service.py CHANGED
@@ -4,11 +4,15 @@ Parses the References section to extract structured citation data.
4
  Uses regex-based extraction with optional Gemini-assisted fallback.
5
  """
6
 
 
7
  import logging
8
  import re
9
  from dataclasses import dataclass
10
  from typing import Optional
11
 
 
 
 
12
  logger = logging.getLogger("app")
13
 
14
 
@@ -53,7 +57,7 @@ def _split_references_section(references_text: str) -> list[str]:
53
  return []
54
 
55
  # Try numbered reference splitting
56
- numbered_refs = re.split(r"\n\s*\[?\d+\]?\s+", references_text)
57
  if len(numbered_refs) > 1:
58
  return [r.strip() for r in numbered_refs if r.strip()]
59
 
@@ -100,7 +104,7 @@ def _parse_single_reference(raw_ref: str) -> ParsedCitation:
100
  author_part = parts[0].strip() if parts else ""
101
 
102
  # Clean numbered prefix from author
103
- author_part = re.sub(r"^\[?\d+\]?\s*", "", author_part).strip()
104
  citation.author = author_part[:200] if author_part else None
105
 
106
  # Extract title: text after year until the next period + capital (journal start)
@@ -121,9 +125,65 @@ def _parse_single_reference(raw_ref: str) -> ParsedCitation:
121
  return citation
122
 
123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  def extract_citations(references_text: str) -> list[ParsedCitation]:
125
  """
126
  Extract structured citations from the references section text.
 
127
 
128
  Args:
129
  references_text: Raw text of the references/bibliography section.
@@ -135,6 +195,14 @@ def extract_citations(references_text: str) -> list[ParsedCitation]:
135
  logger.warning("No references text provided for citation extraction.")
136
  return []
137
 
 
 
 
 
 
 
 
 
138
  raw_refs = _split_references_section(references_text)
139
  logger.info(f"Found {len(raw_refs)} raw reference entries.")
140
 
@@ -148,5 +216,5 @@ def extract_citations(references_text: str) -> list[ParsedCitation]:
148
  except Exception as e:
149
  logger.warning(f"Failed to parse citation: {e} | raw='{raw_ref[:100]}'")
150
 
151
- logger.info(f"Successfully parsed {len(citations)} citations.")
152
  return citations
 
4
  Uses regex-based extraction with optional Gemini-assisted fallback.
5
  """
6
 
7
+ import json
8
  import logging
9
  import re
10
  from dataclasses import dataclass
11
  from typing import Optional
12
 
13
+ import google.generativeai as genai
14
+ from app.config import settings
15
+
16
  logger = logging.getLogger("app")
17
 
18
 
 
57
  return []
58
 
59
  # Try numbered reference splitting
60
+ numbered_refs = re.split(r"\n\s*\[?\d+\]?\.?\s+", references_text)
61
  if len(numbered_refs) > 1:
62
  return [r.strip() for r in numbered_refs if r.strip()]
63
 
 
104
  author_part = parts[0].strip() if parts else ""
105
 
106
  # Clean numbered prefix from author
107
+ author_part = re.sub(r"^\[?\d+\]?\.?\s*", "", author_part).strip()
108
  citation.author = author_part[:200] if author_part else None
109
 
110
  # Extract title: text after year until the next period + capital (journal start)
 
125
  return citation
126
 
127
 
128
+ def _extract_citations_gemini(references_text: str) -> list[ParsedCitation]:
129
+ """Helper to parse citations using Gemini."""
130
+ if not settings.gemini_api_key:
131
+ logger.warning("No Gemini API key available for citation extraction. Using regex fallback.")
132
+ return []
133
+
134
+ prompt = f"""
135
+ You are an expert academic citation parser. Analyze the bibliography/references section below and extract the citations into a JSON array of objects.
136
+ Each object in the array MUST have the following keys:
137
+ - "author": The author or authors of the reference (e.g. "F. Del Vigna, A. Cimino, et al." or "W. Warner and J. Hirschberg").
138
+ - "year": The publication year as a string (e.g. "2017").
139
+ - "title": The title of the paper/book (e.g. "Hate me, hate me not: Hate speech detection on Facebook").
140
+ - "raw_text": The complete original text of this single reference entry.
141
+
142
+ If a field is not present in the reference, use null.
143
+ Do not add any markup or markdown formatting. Return ONLY the raw JSON array.
144
+
145
+ References Section:
146
+ \"\"\"{references_text}\"\"\"
147
+ """
148
+
149
+ try:
150
+ genai.configure(api_key=settings.gemini_api_key)
151
+ model = genai.GenerativeModel(settings.gemini_model)
152
+ # Use structured response config for JSON
153
+ response = model.generate_content(
154
+ prompt,
155
+ generation_config={"response_mime_type": "application/json"}
156
+ )
157
+
158
+ data = json.loads(response.text.strip())
159
+
160
+ # If it's a dict containing a list, find the list
161
+ if isinstance(data, dict):
162
+ for key, val in data.items():
163
+ if isinstance(val, list):
164
+ data = val
165
+ break
166
+
167
+ if isinstance(data, list):
168
+ citations = []
169
+ for item in data:
170
+ citations.append(ParsedCitation(
171
+ author=item.get("author"),
172
+ year=str(item.get("year")) if item.get("year") is not None else None,
173
+ title=item.get("title"),
174
+ raw_text=item.get("raw_text") or item.get("title") or ""
175
+ ))
176
+ return citations
177
+ except Exception as e:
178
+ logger.warning(f"Gemini-assisted citation extraction failed: {e}. Falling back to regex.")
179
+
180
+ return []
181
+
182
+
183
  def extract_citations(references_text: str) -> list[ParsedCitation]:
184
  """
185
  Extract structured citations from the references section text.
186
+ Uses Gemini API first, then falls back to local regex extraction.
187
 
188
  Args:
189
  references_text: Raw text of the references/bibliography section.
 
195
  logger.warning("No references text provided for citation extraction.")
196
  return []
197
 
198
+ # Try Gemini extraction first
199
+ gemini_citations = _extract_citations_gemini(references_text)
200
+ if gemini_citations:
201
+ logger.info(f"Successfully extracted {len(gemini_citations)} citations via Gemini.")
202
+ return gemini_citations
203
+
204
+ # Fallback to local regex-based parsing
205
+ logger.info("Using regex-based citation extraction fallback.")
206
  raw_refs = _split_references_section(references_text)
207
  logger.info(f"Found {len(raw_refs)} raw reference entries.")
208
 
 
216
  except Exception as e:
217
  logger.warning(f"Failed to parse citation: {e} | raw='{raw_ref[:100]}'")
218
 
219
+ logger.info(f"Successfully parsed {len(citations)} citations via regex.")
220
  return citations
AI_Research_Assistant-backend/app/services/paper_service.py CHANGED
@@ -172,7 +172,10 @@ async def process_paper_pipeline(db: AsyncSession, paper_id: str) -> None:
172
 
173
  # Step 3: Citation Extraction
174
  logger.info(f"[Pipeline] Step 2/5: Extracting citations")
175
- citations = extract_citations(sections.references)
 
 
 
176
  for c in citations:
177
  citation_obj = Citation(
178
  paper_id=paper_id,
 
172
 
173
  # Step 3: Citation Extraction
174
  logger.info(f"[Pipeline] Step 2/5: Extracting citations")
175
+ loop = asyncio.get_event_loop()
176
+ citations = await loop.run_in_executor(
177
+ None, extract_citations, sections.references
178
+ )
179
  for c in citations:
180
  citation_obj = Citation(
181
  paper_id=paper_id,