Spaces:
Sleeping
Sleeping
Merge pull request #9 from tAnboyy/feature/review
Browse files- app.py +71 -1
- backend/llm_client.py +23 -0
- backend/rag_service.py +2 -18
- backend/report_service.py +81 -0
app.py
CHANGED
|
@@ -30,6 +30,7 @@ from backend.notebook_service import create_notebook, list_notebooks, rename_not
|
|
| 30 |
from backend.podcast_service import generate_podcast, generate_podcast_audio
|
| 31 |
from backend.chat_service import load_chat
|
| 32 |
from backend.rag_service import rag_chat
|
|
|
|
| 33 |
|
| 34 |
import hashlib
|
| 35 |
_log("4. Imports done.")
|
|
@@ -203,7 +204,47 @@ def _initial_load(profile: gr.OAuthProfile | None = None):
|
|
| 203 |
return state, selected, status, auth_update, gr.update(visible=auth_row_visible), gr.update(visible=bool(user_id)), gr.update(visible=not bool(user_id))
|
| 204 |
|
| 205 |
|
| 206 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
"""Upload PDF files for the selected notebook."""
|
| 208 |
try:
|
| 209 |
user_id = _user_id(profile)
|
|
@@ -697,6 +738,21 @@ with gr.Blocks(
|
|
| 697 |
upload_status = gr.Markdown("", elem_classes=["status"])
|
| 698 |
sources_display = gr.Markdown("")
|
| 699 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 700 |
with gr.Group(elem_classes=["section-card"]):
|
| 701 |
gr.Markdown("**Chat**", elem_classes=["section-title"])
|
| 702 |
gr.Markdown("*Ask questions about your notebook sources. Answers are grounded in retrieved chunks with citations.*")
|
|
@@ -864,6 +920,20 @@ with gr.Blocks(
|
|
| 864 |
outputs=[upload_status],
|
| 865 |
)
|
| 866 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 867 |
podcast_btn.click(
|
| 868 |
_safe_generate_podcast,
|
| 869 |
inputs=[selected_notebook_id],
|
|
|
|
| 30 |
from backend.podcast_service import generate_podcast, generate_podcast_audio
|
| 31 |
from backend.chat_service import load_chat
|
| 32 |
from backend.rag_service import rag_chat
|
| 33 |
+
from backend.report_service import generate_report
|
| 34 |
|
| 35 |
import hashlib
|
| 36 |
_log("4. Imports done.")
|
|
|
|
| 204 |
return state, selected, status, auth_update, gr.update(visible=auth_row_visible), gr.update(visible=bool(user_id)), gr.update(visible=not bool(user_id))
|
| 205 |
|
| 206 |
|
| 207 |
+
REPORT_SCOPE_LABELS = {
|
| 208 |
+
"All sources (PDFs, URLs, text)": "all",
|
| 209 |
+
"PDF uploads only": "pdf",
|
| 210 |
+
"Web URLs only": "url",
|
| 211 |
+
"Uploaded text only": "text",
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
REPORT_SCOPE_DESCRIPTIONS = {
|
| 215 |
+
"all": "PDFs, URLs, and uploaded text",
|
| 216 |
+
"pdf": "uploaded PDFs",
|
| 217 |
+
"url": "ingested web URLs",
|
| 218 |
+
"text": "uploaded text files",
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
DEFAULT_REPORT_SCOPE_LABEL = "All sources (PDFs, URLs, text)"
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def _resolve_report_scope(label: str) -> tuple[str, str]:
|
| 225 |
+
value = REPORT_SCOPE_LABELS.get(label, "all")
|
| 226 |
+
desc = REPORT_SCOPE_DESCRIPTIONS.get(value, "selected sources")
|
| 227 |
+
return value, desc
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def _generate_report(scope_label, notebook_id, profile: gr.OAuthProfile | None):
|
| 231 |
+
scope_value, scope_desc = _resolve_report_scope(scope_label)
|
| 232 |
+
user_id = _user_id(profile)
|
| 233 |
+
if not user_id:
|
| 234 |
+
return "Please sign in with Hugging Face before generating a report.", ""
|
| 235 |
+
if not notebook_id:
|
| 236 |
+
return "Select a notebook first to generate a report.", ""
|
| 237 |
+
try:
|
| 238 |
+
report_text = generate_report(notebook_id, scope_value)
|
| 239 |
+
status = f"Report ready for {scope_desc}."
|
| 240 |
+
return status, report_text
|
| 241 |
+
except ValueError as error:
|
| 242 |
+
return f"⚠️ {error}", ""
|
| 243 |
+
except Exception as error:
|
| 244 |
+
return f"Error generating report: {error}", ""
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def _safe_upload_pdfs(files, selected_id, profile: gr.OAuthProfile | None):
|
| 248 |
"""Upload PDF files for the selected notebook."""
|
| 249 |
try:
|
| 250 |
user_id = _user_id(profile)
|
|
|
|
| 738 |
upload_status = gr.Markdown("", elem_classes=["status"])
|
| 739 |
sources_display = gr.Markdown("")
|
| 740 |
|
| 741 |
+
gr.HTML("<br>")
|
| 742 |
+
with gr.Group(elem_classes=["section-card"]):
|
| 743 |
+
gr.Markdown("**Reports**", elem_classes=["section-title"])
|
| 744 |
+
gr.Markdown("*Generate a concise report based on your uploaded PDFs, ingested URLs, or added text.*")
|
| 745 |
+
with gr.Row(elem_classes=["section-row"]):
|
| 746 |
+
report_scope_dd = gr.Dropdown(
|
| 747 |
+
label="Report scope",
|
| 748 |
+
choices=list(REPORT_SCOPE_LABELS.keys()),
|
| 749 |
+
value=DEFAULT_REPORT_SCOPE_LABEL,
|
| 750 |
+
scale=3,
|
| 751 |
+
)
|
| 752 |
+
report_btn = gr.Button("Generate report", variant="primary", scale=1)
|
| 753 |
+
report_status = gr.Markdown("Select a scope and click generate.", elem_classes=["status"])
|
| 754 |
+
report_output = gr.Markdown("", elem_id="report-output")
|
| 755 |
+
|
| 756 |
with gr.Group(elem_classes=["section-card"]):
|
| 757 |
gr.Markdown("**Chat**", elem_classes=["section-title"])
|
| 758 |
gr.Markdown("*Ask questions about your notebook sources. Answers are grounded in retrieved chunks with citations.*")
|
|
|
|
| 920 |
outputs=[upload_status],
|
| 921 |
)
|
| 922 |
|
| 923 |
+
report_btn.click(
|
| 924 |
+
_generate_report,
|
| 925 |
+
inputs=[report_scope_dd, selected_notebook_id],
|
| 926 |
+
outputs=[report_status, report_output],
|
| 927 |
+
api_name=False,
|
| 928 |
+
)
|
| 929 |
+
|
| 930 |
+
selected_notebook_id.change(
|
| 931 |
+
_load_sources,
|
| 932 |
+
inputs=[selected_notebook_id],
|
| 933 |
+
outputs=[podcast_status, podcast_script],
|
| 934 |
+
api_name=False,
|
| 935 |
+
)
|
| 936 |
+
|
| 937 |
podcast_btn.click(
|
| 938 |
_safe_generate_podcast,
|
| 939 |
inputs=[selected_notebook_id],
|
backend/llm_client.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Helper for shared LLM-based features."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
from openai import OpenAI
|
| 6 |
+
|
| 7 |
+
DEFAULT_MODEL = os.getenv("LLM_MODEL", "meta-llama/Llama-3.2-3B-Instruct:together")
|
| 8 |
+
|
| 9 |
+
_client: OpenAI | None = None
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def get_llm_client() -> OpenAI:
|
| 13 |
+
"""Return a cached OpenAI client configured with the Hugging Face router."""
|
| 14 |
+
global _client
|
| 15 |
+
if _client is None:
|
| 16 |
+
token = os.getenv("HF_TOKEN")
|
| 17 |
+
if not token:
|
| 18 |
+
raise RuntimeError("HF_TOKEN environment variable is required for LLM calls.")
|
| 19 |
+
_client = OpenAI(
|
| 20 |
+
base_url="https://router.huggingface.co/v1",
|
| 21 |
+
api_key=token,
|
| 22 |
+
)
|
| 23 |
+
return _client
|
backend/rag_service.py
CHANGED
|
@@ -1,31 +1,15 @@
|
|
| 1 |
"""RAG chat service - retrieve chunks, call LLM, persist messages."""
|
| 2 |
|
| 3 |
-
import os
|
| 4 |
import re
|
| 5 |
|
| 6 |
-
from openai import OpenAI
|
| 7 |
-
|
| 8 |
from backend.chat_service import save_message, load_chat
|
|
|
|
| 9 |
from backend.retrieval_service import retrieve_chunks
|
| 10 |
|
| 11 |
MAX_HISTORY_MESSAGES = 20
|
| 12 |
# Together AI - you have recent usage. Or :groq for Groq.
|
| 13 |
-
DEFAULT_MODEL = "meta-llama/Llama-3.2-3B-Instruct:together"
|
| 14 |
TOP_K = 5
|
| 15 |
|
| 16 |
-
_client: OpenAI | None = None
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
def _get_client() -> OpenAI:
|
| 20 |
-
global _client
|
| 21 |
-
if _client is None:
|
| 22 |
-
token = os.getenv("HF_TOKEN")
|
| 23 |
-
_client = OpenAI(
|
| 24 |
-
base_url="https://router.huggingface.co/v1",
|
| 25 |
-
api_key=token,
|
| 26 |
-
)
|
| 27 |
-
return _client
|
| 28 |
-
|
| 29 |
|
| 30 |
def _validate_citations(text: str, num_chunks: int) -> str:
|
| 31 |
"""Strip or fix citation numbers [N] where N > num_chunks."""
|
|
@@ -77,7 +61,7 @@ def rag_chat(notebook_id: str, query: str, chat_history: list) -> tuple[str, lis
|
|
| 77 |
messages.append({"role": "user", "content": query})
|
| 78 |
|
| 79 |
try:
|
| 80 |
-
client =
|
| 81 |
response = client.chat.completions.create(
|
| 82 |
model=DEFAULT_MODEL,
|
| 83 |
messages=messages,
|
|
|
|
| 1 |
"""RAG chat service - retrieve chunks, call LLM, persist messages."""
|
| 2 |
|
|
|
|
| 3 |
import re
|
| 4 |
|
|
|
|
|
|
|
| 5 |
from backend.chat_service import save_message, load_chat
|
| 6 |
+
from backend.llm_client import DEFAULT_MODEL, get_llm_client
|
| 7 |
from backend.retrieval_service import retrieve_chunks
|
| 8 |
|
| 9 |
MAX_HISTORY_MESSAGES = 20
|
| 10 |
# Together AI - you have recent usage. Or :groq for Groq.
|
|
|
|
| 11 |
TOP_K = 5
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
def _validate_citations(text: str, num_chunks: int) -> str:
|
| 15 |
"""Strip or fix citation numbers [N] where N > num_chunks."""
|
|
|
|
| 61 |
messages.append({"role": "user", "content": query})
|
| 62 |
|
| 63 |
try:
|
| 64 |
+
client = get_llm_client()
|
| 65 |
response = client.chat.completions.create(
|
| 66 |
model=DEFAULT_MODEL,
|
| 67 |
messages=messages,
|
backend/report_service.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Report generation helper that prompts the LLM with retrieved chunks."""
|
| 2 |
+
|
| 3 |
+
from typing import Final
|
| 4 |
+
|
| 5 |
+
from backend.llm_client import DEFAULT_MODEL, get_llm_client
|
| 6 |
+
from backend.retrieval_service import retrieve_chunks
|
| 7 |
+
|
| 8 |
+
MAX_CONTEXT_ITEMS: Final[int] = 8
|
| 9 |
+
REPORT_SCOPE_DESCRIPTIONS = {
|
| 10 |
+
"all": "PDFs, websites, and uploaded text",
|
| 11 |
+
"pdf": "PDF uploads",
|
| 12 |
+
"url": "ingested websites",
|
| 13 |
+
"text": "uploaded text files",
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _is_pdf_metadata(metadata: dict) -> bool:
|
| 18 |
+
name = (metadata.get("file_name") or "").lower()
|
| 19 |
+
path = (metadata.get("file_path") or "").lower()
|
| 20 |
+
if name.endswith(".pdf") or path.endswith(".pdf"):
|
| 21 |
+
return True
|
| 22 |
+
return False
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _is_text_metadata(metadata: dict) -> bool:
|
| 26 |
+
name = (metadata.get("file_name") or "").lower()
|
| 27 |
+
return name.endswith(".txt")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _matches_scope(chunk: dict, scope: str) -> bool:
|
| 31 |
+
if scope == "all":
|
| 32 |
+
return True
|
| 33 |
+
metadata = chunk.get("metadata") or {}
|
| 34 |
+
if scope == "pdf":
|
| 35 |
+
return _is_pdf_metadata(metadata)
|
| 36 |
+
if scope == "text":
|
| 37 |
+
return _is_text_metadata(metadata)
|
| 38 |
+
if scope == "url":
|
| 39 |
+
return bool(metadata.get("url"))
|
| 40 |
+
return True
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def generate_report(notebook_id: str, scope: str = "all") -> str:
|
| 44 |
+
"""Return a report string using the provided notebook sources."""
|
| 45 |
+
normalized_scope = scope if scope in REPORT_SCOPE_DESCRIPTIONS else "all"
|
| 46 |
+
desc = REPORT_SCOPE_DESCRIPTIONS[normalized_scope]
|
| 47 |
+
chunks = retrieve_chunks(notebook_id, f"report summary for {desc}", top_k=16)
|
| 48 |
+
filtered = [chunk for chunk in chunks if _matches_scope(chunk, normalized_scope)]
|
| 49 |
+
if not filtered:
|
| 50 |
+
raise ValueError(f"No {desc} chunks are available yet.")
|
| 51 |
+
|
| 52 |
+
context_items = filtered[:MAX_CONTEXT_ITEMS]
|
| 53 |
+
context_lines = [f"[{idx}] {item['content']}" for idx, item in enumerate(context_items, start=1)]
|
| 54 |
+
context_block = "\n\n".join(context_lines)
|
| 55 |
+
|
| 56 |
+
system_content = (
|
| 57 |
+
f"You are NotebookLM's assistant. Using the numbered context items below that come from {desc},"
|
| 58 |
+
"write a concise report that sticks to the facts."
|
| 59 |
+
" Cite every referenced statement with the matching [n]."
|
| 60 |
+
f"\n\nContext:\n{context_block}"
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
user_message = (
|
| 64 |
+
"Create a report with at least the sections Summary, Key Findings, and Recommendations."
|
| 65 |
+
" Bullet points are fine."
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
client = get_llm_client()
|
| 69 |
+
response = client.chat.completions.create(
|
| 70 |
+
model=DEFAULT_MODEL,
|
| 71 |
+
messages=[
|
| 72 |
+
{"role": "system", "content": system_content},
|
| 73 |
+
{"role": "user", "content": user_message},
|
| 74 |
+
],
|
| 75 |
+
max_tokens=700,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
report_text = response.choices[0].message.content.strip() if response.choices else ""
|
| 79 |
+
if not report_text:
|
| 80 |
+
raise ValueError("The report generator returned an empty response.")
|
| 81 |
+
return report_text
|