File size: 11,615 Bytes
1a83899
 
 
 
 
 
 
fb60b9f
 
 
 
 
1a83899
fb60b9f
 
 
1a83899
 
 
 
 
 
 
 
 
fb60b9f
 
 
 
 
 
 
 
 
 
 
 
1a83899
fb60b9f
1a83899
 
 
 
 
 
fb60b9f
 
 
 
1a83899
fb60b9f
 
 
1a83899
 
 
 
 
 
 
 
 
fb60b9f
 
1a83899
fb60b9f
 
1a83899
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb60b9f
1a83899
fb60b9f
 
 
 
 
 
1a83899
fb60b9f
 
 
 
 
 
1a83899
 
 
fb60b9f
1a83899
 
 
 
fb60b9f
 
 
 
 
 
1a83899
 
 
 
 
 
fb60b9f
1a83899
 
 
 
 
 
 
fb60b9f
1a83899
fb60b9f
1a83899
 
 
 
fb60b9f
 
1a83899
 
 
 
 
 
fb60b9f
1a83899
 
 
fb60b9f
 
 
 
1a83899
 
 
 
 
 
 
 
 
 
 
 
 
fb60b9f
1a83899
 
fb60b9f
 
1a83899
fb60b9f
1a83899
 
 
 
 
 
 
 
 
 
fb60b9f
1a83899
 
 
fb60b9f
 
1a83899
 
 
fb60b9f
1a83899
 
 
 
 
fb60b9f
 
 
 
 
1a83899
fb60b9f
 
 
1a83899
 
 
fb60b9f
 
1a83899
 
 
 
 
fb60b9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a83899
fb60b9f
 
 
1a83899
fb60b9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a83899
 
 
 
 
 
 
 
 
fb60b9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a83899
fb60b9f
1a83899
 
fb60b9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
import os
import io
import re
import json
import base64
import requests
import numpy as np
import streamlit as st
from pypdf import PdfReader
import matplotlib.pyplot as plt

# -----------------------------
# Config / Secrets (safe)
# -----------------------------
st.set_page_config(page_title="PDF Summarizer + Audio + QA", page_icon="πŸ“„", layout="wide")

# Prefer environment variable (Spaces sets secrets as env vars), *then* try st.secrets safely.
HF_TOKEN = os.environ.get("HF_TOKEN", "")
if not HF_TOKEN:
    try:
        # Access st.secrets inside try/except so we don't crash when no secrets file exists.
        HF_TOKEN = st.secrets.get("HF_TOKEN", "") if hasattr(st, "secrets") else ""
    except Exception:
        HF_TOKEN = ""

HEADERS_JSON = {
    "Authorization": f"Bearer {HF_TOKEN}" if HF_TOKEN else "",
    "Content-Type": "application/json",
    "Accept": "application/json",
}

SUMMARIZER_MODEL = "facebook/bart-large-cnn"
TTS_MODEL = "facebook/mms-tts-eng"
EMB_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
QA_MODEL = "deepset/roberta-base-squad2"

# -----------------------------
# Helper: Hugging Face inference
# -----------------------------
def hf_infer_json(model_id: str, payload: dict, router=False, accept=None, timeout=120):
    """
    Send request to Hugging Face Hosted Inference API.
    If `router=True` we'll use the router base path (useful for some pipelines).
    If backend returns binary (audio), this returns raw bytes.
    """
    if router:
        url = f"https://router.huggingface.co/hf-inference/models/{model_id}"
    else:
        url = f"https://api-inference.huggingface.co/models/{model_id}"

    headers = HEADERS_JSON.copy()
    if accept:
        headers["Accept"] = accept

    try:
        r = requests.post(url, headers=headers, data=json.dumps(payload), timeout=timeout)
        r.raise_for_status()
    except requests.exceptions.RequestException as e:
        # Bubble up a useful message
        raise RuntimeError(f"Hugging Face request failed: {e}")

    # Try to decode JSON; if fails, return bytes/content
    try:
        return r.json()
    except ValueError:
        return r.content

# -----------------------------
# Text / PDF utilities
# -----------------------------
def extract_text_from_pdf(file) -> str:
    reader = PdfReader(file)
    pages = []
    for p in reader.pages:
        try:
            pages.append(p.extract_text() or "")
        except Exception:
            pages.append("")
    return "\n".join(pages)

def clean_text(s: str) -> str:
    return re.sub(r"\s+", " ", s).strip()

def split_into_chunks(text: str, max_chars: int = 1800, overlap: int = 200):
    text = clean_text(text)
    chunks = []
    i = 0
    while i < len(text):
        chunk = text[i:i+max_chars]
        last_dot = chunk.rfind(". ")
        if last_dot > 400:
            chunk = chunk[: last_dot + 1]
            i += last_dot + 1 - overlap
        else:
            i += max_chars - overlap
        chunks.append(chunk.strip())
    return [c for c in chunks if c]

# -----------------------------
# Embeddings + similarity
# -----------------------------
def embed_texts(texts):
    """
    Calls the feature-extraction pipeline on the router endpoint.
    Returns numpy array shape (n_texts, dim)
    """
    url = f"https://router.huggingface.co/hf-inference/models/{EMB_MODEL}/pipeline/feature-extraction"
    headers = {
        "Authorization": f"Bearer {HF_TOKEN}" if HF_TOKEN else "",
        "Content-Type": "application/json",
        "Accept": "application/json",
    }
    try:
        r = requests.post(url, headers=headers, data=json.dumps({"inputs": texts}), timeout=120)
        r.raise_for_status()
    except requests.exceptions.RequestException as e:
        raise RuntimeError(f"Embedding request failed: {e}")

    arr = np.array(r.json(), dtype=np.float32)

    # Cases:
    # - arr.ndim == 1 -> single vector (dim,) -> reshape to (1,dim)
    # - arr.ndim == 2 -> batch of vectors (n, dim) -> return as-is
    # - arr.ndim == 3 -> model returned token-level vectors per item: mean-pool per item -> (n, dim)
    if arr.ndim == 1:
        return arr.reshape(1, -1)
    if arr.ndim == 2:
        return arr
    if arr.ndim == 3:
        pooled = np.array([a.mean(axis=0) for a in arr])
        return pooled
    # Fallback
    return arr.reshape(arr.shape[0], -1)

def cosine_sim(a, b):
    """
    a: (m, d), b: (n, d) -> returns (m, n)
    """
    a_n = a / (np.linalg.norm(a, axis=-1, keepdims=True) + 1e-8)
    b_n = b / (np.linalg.norm(b, axis=-1, keepdims=True) + 1e-8)
    return a_n @ b_n.T

# -----------------------------
# Summarization
# -----------------------------
def summarize_long_text(text: str, per_chunk_max_len=220, final_max_len=250):
    chunks = split_into_chunks(text, max_chars=1800, overlap=200)
    mini_summaries = []
    for c in chunks:
        try:
            out = hf_infer_json(
                SUMMARIZER_MODEL,
                {"inputs": c, "parameters": {"max_length": per_chunk_max_len, "min_length": 60, "do_sample": False}},
                router=False,
            )
        except Exception as e:
            # if API fails, include the chunk (truncated) as fallback
            mini_summaries.append(c[:1000])
            continue

        # Hosted inference often returns a list of dicts with 'summary_text'
        if isinstance(out, list) and len(out) and isinstance(out[0], dict) and "summary_text" in out[0]:
            mini_summaries.append(out[0]["summary_text"])
        elif isinstance(out, dict) and "summary_text" in out:
            mini_summaries.append(out["summary_text"])
        else:
            mini_summaries.append(c[:1000])

    joined = " ".join(mini_summaries)
    try:
        final = hf_infer_json(
            SUMMARIZER_MODEL,
            {"inputs": joined, "parameters": {"max_length": final_max_len, "min_length": 80, "do_sample": False}},
            router=False,
        )
    except Exception:
        return joined[:1200], chunks

    if isinstance(final, list) and len(final) and isinstance(final[0], dict) and "summary_text" in final[0]:
        return final[0]["summary_text"], chunks
    if isinstance(final, dict) and "summary_text" in final:
        return final["summary_text"], chunks

    return joined[:1200], chunks

# -----------------------------
# TTS
# -----------------------------
def tts_wav_bytes(text: str) -> bytes:
    try:
        res = hf_infer_json(TTS_MODEL, {"inputs": text}, router=False, accept="audio/wav", timeout=180)
    except Exception as e:
        raise RuntimeError(f"TTS request failed: {e}")

    if isinstance(res, (bytes, bytearray)):
        return res
    if isinstance(res, dict) and "audio" in res:
        try:
            return base64.b64decode(res["audio"])
        except Exception:
            pass
    raise RuntimeError("TTS API did not return audio bytes.")

# -----------------------------
# Visualization helper
# -----------------------------
def make_word_freq_chart(text: str, top_k=20):
    text = text.lower()
    stop = set(
        (
            "the a an and of to in is are for with on by as at this that from be was were it its it's into or if not your you we they their our can may such more most other also than which".split()
        )
    )
    tokens = re.findall(r"[a-zA-Z]{3,}", text)
    freq = {}
    for t in tokens:
        if t in stop:
            continue
        freq[t] = freq.get(t, 0) + 1
    items = sorted(freq.items(), key=lambda x: x[1], reverse=True)[:top_k]
    if not items:
        st.info("Not enough text to show a frequency chart.")
        return
    words, counts = zip(*items)
    fig = plt.figure()
    plt.bar(words, counts)
    plt.xticks(rotation=60, ha="right")
    plt.title("Top word frequencies")
    plt.tight_layout()
    st.pyplot(fig)

# -----------------------------
# UI
# -----------------------------
st.title("πŸ“„ PDF β†’ Summary Β· πŸ”Š Audio Β· πŸ“Š Chart Β· ❓ Q&A")
st.caption("Powered by Hugging Face Hosted Inference API (free models).")

if not HF_TOKEN:
    st.warning("No HF_TOKEN found. Add HF_TOKEN in Space Settings β†’ Secrets (recommended). The app will still run but HF API calls will fail without a token.")

uploaded = st.file_uploader("Upload a PDF", type=["pdf"])

# session state
if "doc_text" not in st.session_state:
    st.session_state.doc_text = ""
    st.session_state.chunks = []
    st.session_state.chunk_vecs = None
    st.session_state.summary = ""

if uploaded:
    with st.spinner("Extracting text..."):
        text = extract_text_from_pdf(uploaded)
        st.session_state.doc_text = text
        st.success(f"Loaded {len(text)} characters.")

    st.write("### Actions")
    c1, c2, c3 = st.columns(3)

    with c1:
        if st.button("πŸ“ Summarize"):
            with st.spinner("Summarizing..."):
                try:
                    summary, chunks = summarize_long_text(st.session_state.doc_text)
                    st.session_state.summary = summary
                    st.session_state.chunks = chunks
                    st.success("Summary ready.")
                    st.write("#### Summary")
                    st.write(summary)
                except Exception as e:
                    st.error(f"Summarization failed: {e}")

    with c2:
        if st.button("πŸ”Š Generate Audio (summary)"):
            target_text = st.session_state.summary or st.session_state.doc_text[:1200]
            with st.spinner("Generating audio..."):
                try:
                    wav = tts_wav_bytes(target_text)
                    st.audio(wav, format="audio/wav")
                    st.success("Audio ready.")
                except Exception as e:
                    st.error(f"TTS failed: {e}")

    with c3:
        if st.button("πŸ“Š Show Word-Frequency Chart"):
            with st.spinner("Building chart..."):
                make_word_freq_chart(st.session_state.doc_text)

    st.write("---")
    st.subheader("Ask questions about the PDF")
    question = st.text_input("Your question")
    if st.button("Answer"):
        if not st.session_state.chunks:
            st.session_state.chunks = split_into_chunks(st.session_state.doc_text)
        with st.spinner("Thinking..."):
            try:
                # embed once/cache
                if st.session_state.chunk_vecs is None:
                    st.session_state.chunk_vecs = embed_texts(st.session_state.chunks)
                vecs = st.session_state.chunk_vecs

                q_vec = embed_texts([question])
                sims = cosine_sim(q_vec, vecs).flatten()
                top_idx = np.argsort(sims)[::-1][:3]
                context = "\n".join([st.session_state.chunks[i] for i in top_idx])

                qa_out = hf_infer_json(QA_MODEL, {"inputs": {"question": question, "context": context}}, router=False)
                if isinstance(qa_out, dict):
                    ans = qa_out.get("answer", "")
                    score = qa_out.get("score", 0.0)
                elif isinstance(qa_out, list) and len(qa_out) and isinstance(qa_out[0], dict):
                    ans = qa_out[0].get("answer", "")
                    score = qa_out[0].get("score", 0.0)
                else:
                    ans, score = "", 0.0

                st.write("**Answer:**", ans or "_(no confident answer)_")
                st.caption(f"Confidence: {score:.3f}")
                with st.expander("Context used"):
                    st.write(context)
            except Exception as e:
                st.error(f"QA failed: {e}")

else:
    st.info("Upload a PDF to get started.")