ChatBotsTA commited on
Commit
fb60b9f
Β·
verified Β·
1 Parent(s): 8a696c1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +240 -0
app.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Cell 9
2
+ app_code = r'''
3
+ import os, io, re, json, base64, requests, numpy as np
4
+ import streamlit as st
5
+ from pypdf import PdfReader
6
+ import matplotlib.pyplot as plt
7
+
8
+ # -----------------------------
9
+ # Config
10
+ # -----------------------------
11
+ st.set_page_config(page_title="PDF Summarizer + Audio + QA", page_icon="πŸ“„", layout="wide")
12
+
13
+ HF_TOKEN = os.environ.get("HF_TOKEN", st.secrets.get("HF_TOKEN", ""))
14
+ HEADERS_JSON = {
15
+ "Authorization": f"Bearer {HF_TOKEN}" if HF_TOKEN else "",
16
+ "Content-Type": "application/json",
17
+ "Accept": "application/json",
18
+ }
19
+
20
+ SUMMARIZER_MODEL = "facebook/bart-large-cnn"
21
+ TTS_MODEL = "facebook/mms-tts-eng"
22
+ EMB_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
23
+ QA_MODEL = "deepset/roberta-base-squad2"
24
+
25
+ # -----------------------------
26
+ # API helpers
27
+ # -----------------------------
28
+ def hf_infer_json(model_id: str, payload: dict, router=False, accept=None):
29
+ if router:
30
+ url = f"https://router.huggingface.co/hf-inference/models/{model_id}"
31
+ else:
32
+ url = f"https://api-inference.huggingface.co/models/{model_id}"
33
+ headers = HEADERS_JSON.copy()
34
+ if accept:
35
+ headers["Accept"] = accept
36
+ r = requests.post(url, headers=headers, data=json.dumps(payload), timeout=120)
37
+ r.raise_for_status()
38
+ try:
39
+ return r.json()
40
+ except requests.exceptions.JSONDecodeError:
41
+ return r.content
42
+
43
+ def split_into_chunks(text: str, max_chars: int = 1800, overlap: int = 200):
44
+ text = re.sub(r"\s+", " ", text).strip()
45
+ chunks = []
46
+ i = 0
47
+ while i < len(text):
48
+ chunk = text[i:i+max_chars]
49
+ last_dot = chunk.rfind(". ")
50
+ if last_dot > 400:
51
+ chunk = chunk[:last_dot+1]
52
+ i += last_dot + 1 - overlap
53
+ else:
54
+ i += max_chars - overlap
55
+ chunks.append(chunk.strip())
56
+ return [c for c in chunks if c]
57
+
58
+ def embed_texts(texts):
59
+ url = f"https://router.huggingface.co/hf-inference/models/{EMB_MODEL}/pipeline/feature-extraction"
60
+ headers = {
61
+ "Authorization": f"Bearer {HF_TOKEN}" if HF_TOKEN else "",
62
+ "Content-Type": "application/json",
63
+ "Accept": "application/json",
64
+ }
65
+ r = requests.post(url, headers=headers, data=json.dumps({"inputs": texts}), timeout=120)
66
+ r.raise_for_status()
67
+ arr = np.array(r.json(), dtype=np.float32)
68
+ if arr.ndim == 2:
69
+ return arr.mean(axis=0, keepdims=True)
70
+ if arr.ndim == 3:
71
+ pooled = [a.mean(axis=0) for a in arr]
72
+ return np.vstack(pooled)
73
+ return np.array(arr)
74
+
75
+ def cosine_sim(a, b):
76
+ a = a / (np.linalg.norm(a, axis=-1, keepdims=True) + 1e-8)
77
+ b = b / (np.linalg.norm(b, axis=-1, keepdims=True) + 1e-8)
78
+ return a @ b.T
79
+
80
+ def summarize_long_text(text: str, per_chunk_max_len=220, final_max_len=250):
81
+ chunks = split_into_chunks(text, max_chars=1800, overlap=200)
82
+ mini_summaries = []
83
+ for c in chunks:
84
+ out = hf_infer_json(
85
+ SUMMARIZER_MODEL,
86
+ {"inputs": c, "parameters": {"max_length": per_chunk_max_len, "min_length": 60, "do_sample": False}},
87
+ router=False
88
+ )
89
+ if isinstance(out, list) and len(out) and "summary_text" in out[0]:
90
+ mini_summaries.append(out[0]["summary_text"])
91
+ else:
92
+ mini_summaries.append(c[:1000])
93
+ joined = " ".join(mini_summaries)
94
+ final = hf_infer_json(
95
+ SUMMARIZER_MODEL,
96
+ {"inputs": joined, "parameters": {"max_length": final_max_len, "min_length": 80, "do_sample": False}},
97
+ router=False
98
+ )
99
+ if isinstance(final, list) and len(final) and "summary_text" in final[0]:
100
+ return final[0]["summary_text"], chunks
101
+ return joined[:1200], chunks
102
+
103
+ def tts_wav_bytes(text: str) -> bytes:
104
+ res = hf_infer_json(TTS_MODEL, {"inputs": text}, router=False, accept="audio/wav")
105
+ if isinstance(res, (bytes, bytearray)):
106
+ return res
107
+ if isinstance(res, dict) and "audio" in res:
108
+ try:
109
+ return base64.b64decode(res["audio"])
110
+ except:
111
+ pass
112
+ raise RuntimeError("TTS API did not return audio bytes.")
113
+
114
+ def extract_text_from_pdf(file) -> str:
115
+ reader = PdfReader(file)
116
+ pages = []
117
+ for p in reader.pages:
118
+ try:
119
+ pages.append(p.extract_text() or "")
120
+ except:
121
+ pages.append("")
122
+ return "\n".join(pages)
123
+
124
+ def make_word_freq_chart(text: str, top_k=20):
125
+ text = text.lower()
126
+ # lightweight stopword list
127
+ 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()))
128
+ tokens = re.findall(r"[a-zA-Z]{3,}", text)
129
+ freq = {}
130
+ for t in tokens:
131
+ if t in stop:
132
+ continue
133
+ freq[t] = freq.get(t, 0) + 1
134
+ items = sorted(freq.items(), key=lambda x: x[1], reverse=True)[:top_k]
135
+ if not items:
136
+ st.info("Not enough text to show a frequency chart.")
137
+ return
138
+ words, counts = zip(*items)
139
+ fig = plt.figure()
140
+ plt.bar(words, counts)
141
+ plt.xticks(rotation=60, ha="right")
142
+ plt.title("Top word frequencies")
143
+ plt.tight_layout()
144
+ st.pyplot(fig)
145
+
146
+ # -----------------------------
147
+ # UI
148
+ # -----------------------------
149
+ st.title("πŸ“„ PDF β†’ Summary Β· πŸ”Š Audio Β· πŸ“Š Chart Β· ❓ Q&A")
150
+ st.caption("Powered by Hugging Face Hosted Inference API (free models).")
151
+
152
+ if not HF_TOKEN:
153
+ st.warning("Set HF_TOKEN in environment or in your Space secrets to use the Hosted Inference API.")
154
+
155
+ uploaded = st.file_uploader("Upload a PDF", type=["pdf"])
156
+
157
+ if "doc_text" not in st.session_state:
158
+ st.session_state.doc_text = ""
159
+ st.session_state.chunks = []
160
+ st.session_state.chunk_vecs = None
161
+ st.session_state.summary = ""
162
+
163
+ if uploaded:
164
+ with st.spinner("Extracting text..."):
165
+ text = extract_text_from_pdf(uploaded)
166
+ st.session_state.doc_text = text
167
+ st.success(f"Loaded {len(text)} characters.")
168
+
169
+ st.write("### Actions")
170
+ c1, c2, c3 = st.columns(3)
171
+
172
+ with c1:
173
+ if st.button("πŸ“ Summarize"):
174
+ with st.spinner("Summarizing..."):
175
+ summary, chunks = summarize_long_text(st.session_state.doc_text)
176
+ st.session_state.summary = summary
177
+ st.session_state.chunks = chunks
178
+ st.success("Summary ready.")
179
+ st.write("#### Summary")
180
+ st.write(summary)
181
+
182
+ with c2:
183
+ if st.button("πŸ”Š Generate Audio (summary)"):
184
+ target_text = st.session_state.summary or st.session_state.doc_text[:1200]
185
+ with st.spinner("Generating audio..."):
186
+ try:
187
+ wav = tts_wav_bytes(target_text)
188
+ st.audio(wav, format="audio/wav")
189
+ st.success("Audio ready.")
190
+ except Exception as e:
191
+ st.error(f"TTS failed: {e}")
192
+
193
+ with c3:
194
+ if st.button("πŸ“Š Show Word-Frequency Chart"):
195
+ with st.spinner("Building chart..."):
196
+ make_word_freq_chart(st.session_state.doc_text)
197
+
198
+ st.write("---")
199
+ st.subheader("Ask questions about the PDF")
200
+ question = st.text_input("Your question")
201
+ if st.button("Answer"):
202
+ if not st.session_state.chunks:
203
+ st.session_state.chunks = split_into_chunks(st.session_state.doc_text)
204
+ with st.spinner("Thinking..."):
205
+ try:
206
+ # embed once/cache
207
+ if st.session_state.chunk_vecs is None:
208
+ vecs = embed_texts(st.session_state.chunks)
209
+ st.session_state.chunk_vecs = vecs
210
+ else:
211
+ vecs = st.session_state.chunk_vecs
212
+
213
+ # question embedding
214
+ q_vec = embed_texts([question])
215
+ sims = cosine_sim(q_vec, vecs).flatten()
216
+ top_idx = np.argsort(sims)[::-1][:3]
217
+ context = "\n".join([st.session_state.chunks[i] for i in top_idx])
218
+
219
+ qa_out = hf_infer_json(QA_MODEL, {"inputs": {"question": question, "context": context}}, router=False)
220
+ if isinstance(qa_out, dict):
221
+ ans = qa_out.get("answer", "")
222
+ score = qa_out.get("score", 0.0)
223
+ elif isinstance(qa_out, list) and len(qa_out) and isinstance(qa_out[0], dict):
224
+ ans = qa_out[0].get("answer", "")
225
+ score = qa_out[0].get("score", 0.0)
226
+ else:
227
+ ans, score = "", 0.0
228
+
229
+ st.write("**Answer:**", ans or "_(no confident answer)_")
230
+ st.caption(f"Confidence: {score:.3f}")
231
+ with st.expander("Context used"):
232
+ st.write(context)
233
+ except Exception as e:
234
+ st.error(f"QA failed: {e}")
235
+
236
+ else:
237
+ st.info("Upload a PDF to get started.")
238
+ '''
239
+ Path("app.py").write_text(app_code, encoding="utf-8")
240
+ print("Wrote app.py")