Moonturtle19 commited on
Commit
29b3245
·
verified ·
1 Parent(s): 3345e00

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +359 -52
app.py CHANGED
@@ -1,78 +1,373 @@
 
1
  import os
 
 
 
 
2
  import gradio as gr
3
  from google import genai
4
  from google.genai import types
 
5
 
6
 
 
 
 
 
7
  MODEL_NAME = "gemini-3.5-flash-lite"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  def respond(
11
  message,
12
- history: list[dict[str, str]],
13
  system_message,
14
  max_tokens,
15
  temperature,
16
  top_p,
17
  ):
18
- """
19
- Stream responses from the Gemini API.
20
- Set GEMINI_API_KEY in your Hugging Face Space secrets.
21
- """
22
-
23
  api_key = os.getenv("GEMINI_API_KEY")
 
24
  if not api_key:
25
  yield (
26
  "Configuration error: GEMINI_API_KEY is missing. "
27
- "Add it under your Hugging Face Space Settings → Secrets, "
28
- "then restart the Space."
29
  )
30
  return
31
 
32
- client = genai.Client(api_key=api_key)
 
 
 
 
33
 
34
- # Convert Gradio's chat history into Gemini's conversation format.
35
- contents = []
36
- for item in history or []:
37
- role = item.get("role")
38
- content = item.get("content")
39
 
40
- # This app uses text-only chat messages.
41
- if not isinstance(content, str) or not content.strip():
42
- continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
- if role == "user":
45
- contents.append(
46
- types.Content(
47
- role="user",
48
- parts=[types.Part.from_text(text=content)],
 
49
  )
50
- )
51
- elif role == "assistant":
52
- contents.append(
53
- types.Content(
54
- role="model",
55
- parts=[types.Part.from_text(text=content)],
 
56
  )
 
 
 
 
 
57
  )
 
58
 
59
- # Add the latest user message.
60
- contents.append(
61
- types.Content(
62
- role="user",
63
- parts=[types.Part.from_text(text=message)],
64
  )
65
- )
66
 
67
- config = types.GenerateContentConfig(
68
- system_instruction=system_message or "You are a friendly chatbot.",
69
- max_output_tokens=int(max_tokens),
70
- temperature=float(temperature),
71
- top_p=float(top_p),
72
- )
73
 
74
- answer = ""
75
- try:
76
  for chunk in client.models.generate_content_stream(
77
  model=MODEL_NAME,
78
  contents=contents,
@@ -86,43 +381,55 @@ def respond(
86
  yield "I couldn't generate a response. Please try again."
87
 
88
  except Exception as exc:
89
- # Keep technical details in Space logs; show a useful message to users.
90
  print(f"Gemini API error: {type(exc).__name__}: {exc}")
 
91
  yield (
92
  "Sorry, the AI service couldn't complete your request. "
93
- "Please try again in a moment. If the issue continues, "
94
- "check the Space logs and your Gemini API quota."
95
  )
96
 
97
 
 
 
 
 
98
  chatbot = gr.ChatInterface(
99
  fn=respond,
100
  additional_inputs=[
101
- gr.Textbox(value="You are a friendly chatbot.", label="System message"),
 
 
 
102
  gr.Slider(
103
  minimum=1,
104
  maximum=2048,
105
- value=512,
106
  step=1,
107
- label="Max new tokens",
108
  ),
109
  gr.Slider(
110
  minimum=0.1,
111
  maximum=2.0,
112
- value=0.7,
113
  step=0.1,
114
- label="Temperature",
115
  ),
116
  gr.Slider(
117
  minimum=0.1,
118
  maximum=1.0,
119
  value=0.95,
120
  step=0.05,
121
- label="Top-p (nucleus sampling)",
122
  ),
123
  ],
124
- title="NBV Chatbot",
 
 
 
 
125
  )
126
 
 
127
  if __name__ == "__main__":
128
  chatbot.launch()
 
 
1
+
2
  import os
3
+ import re
4
+ import csv
5
+ from pathlib import Path
6
+
7
  import gradio as gr
8
  from google import genai
9
  from google.genai import types
10
+ from pypdf import PdfReader
11
 
12
 
13
+ # --------------------------------------------------
14
+ # CONFIGURATION
15
+ # --------------------------------------------------
16
+
17
  MODEL_NAME = "gemini-3.5-flash-lite"
18
+ DATA_ROOT = Path(__file__).parent
19
+
20
+ MAX_CSV_RESULTS = 12
21
+ MAX_DOCUMENT_RESULTS = 6
22
+ MAX_CONTEXT_CHARS = 18000
23
+
24
+ STOP_WORDS = {
25
+ "the", "a", "an", "is", "are", "was", "were", "what",
26
+ "which", "who", "how", "why", "when", "where", "show",
27
+ "find", "tell", "me", "about", "for", "of", "in", "on",
28
+ "to", "and", "or", "with", "from", "that", "this", "do",
29
+ "does", "can", "could", "would", "should", "please",
30
+ "startup", "startups", "company", "companies"
31
+ }
32
+
33
+ NBV_INSTRUCTIONS = """
34
+ You are the NBV Investment Research Assistant.
35
+
36
+ Your job is to help users understand Next Bharat Ventures (NBV),
37
+ its investment thesis, historical startup pipeline, portfolio,
38
+ cohorts and potential investment opportunities.
39
+
40
+ IMPORTANT RULES:
41
+
42
+ 1. Use the retrieved NBV files as your primary source for internal
43
+ information.
44
+
45
+ 2. Never invent startup names, investment decisions, cheque sizes,
46
+ revenue figures, founder details or cohort information.
47
+
48
+ 3. Distinguish between:
49
+ - Internal startup database records
50
+ - Publicly available information
51
+ - Your own analysis or inference
52
+
53
+ 4. A startup appearing in the pipeline does not automatically mean
54
+ NBV invested in it.
55
+
56
+ 5. Preserve the original status and cohort information from the
57
+ database. Do not silently merge records with similar names.
58
+
59
+ 6. If information is missing from the files, explicitly say so.
60
+
61
+ 7. When evaluating a new startup, consider:
62
+ - Problem and target customer
63
+ - India 2 / India 3 relevance
64
+ - Impact and livelihood creation
65
+ - Business model
66
+ - Traction and commercial viability
67
+ - Scalability
68
+ - Fit with NBV's investment thesis
69
+
70
+ 8. Separate facts from recommendations. Explain why a startup
71
+ appears to fit or not fit the thesis.
72
+
73
+ 9. When comparing companies, use actual retrieved records.
74
+ Do not manufacture comparisons.
75
+
76
+ 10. Keep answers clear, practical and research-oriented.
77
+ Mention the source filename wherever possible.
78
+ """
79
+
80
+
81
+ # --------------------------------------------------
82
+ # TEXT PROCESSING
83
+ # --------------------------------------------------
84
+
85
+ def tokenize(text):
86
+ words = re.findall(r"[a-zA-Z0-9]+", str(text).lower())
87
+ return [word for word in words if word not in STOP_WORDS]
88
+
89
+
90
+ def score_text(query, content):
91
+ query_tokens = set(tokenize(query))
92
+ content_tokens = set(tokenize(content))
93
+
94
+ if not query_tokens:
95
+ return 0
96
+
97
+ overlap = len(query_tokens.intersection(content_tokens))
98
+ score = overlap / len(query_tokens)
99
+
100
+ if query.strip().lower() in content.lower():
101
+ score += 2
102
+
103
+ return score
104
+
105
+
106
+ # --------------------------------------------------
107
+ # LOAD CSV FILES
108
+ # --------------------------------------------------
109
+
110
+ def load_csv_records():
111
+ records = []
112
+
113
+ for file_path in DATA_ROOT.rglob("*.csv"):
114
+ if any(part.startswith(".") for part in file_path.parts):
115
+ continue
116
+
117
+ try:
118
+ with open(
119
+ file_path,
120
+ "r",
121
+ encoding="utf-8-sig",
122
+ newline=""
123
+ ) as file:
124
+ reader = csv.DictReader(file)
125
+
126
+ for row_number, row in enumerate(reader, start=2):
127
+ fields = []
128
+
129
+ for key, value in row.items():
130
+ if value and str(value).strip():
131
+ fields.append(f"{key}: {value}")
132
+
133
+ if fields:
134
+ records.append({
135
+ "source": str(file_path.relative_to(DATA_ROOT)),
136
+ "row": row_number,
137
+ "content": "\n".join(fields)
138
+ })
139
+
140
+ except Exception as exc:
141
+ print(f"Could not read CSV {file_path}: {exc}")
142
+
143
+ print(f"Loaded {len(records)} CSV records.")
144
+ return records
145
+
146
+
147
+ # --------------------------------------------------
148
+ # LOAD DOCUMENT FILES
149
+ # --------------------------------------------------
150
+
151
+ def split_into_chunks(text, max_chars=1200):
152
+ paragraphs = [
153
+ p.strip() for p in text.split("\n")
154
+ if p.strip()
155
+ ]
156
+
157
+ chunks = []
158
+ current = ""
159
+
160
+ for paragraph in paragraphs:
161
+ if len(current) + len(paragraph) > max_chars and current:
162
+ chunks.append(current)
163
+ current = paragraph
164
+ else:
165
+ current += "\n" + paragraph
166
+
167
+ if current:
168
+ chunks.append(current)
169
+
170
+ return chunks
171
+
172
+
173
+ def load_documents():
174
+ documents = []
175
+
176
+ supported_extensions = {".md", ".txt", ".pdf"}
177
+
178
+ for file_path in DATA_ROOT.rglob("*"):
179
+ if not file_path.is_file():
180
+ continue
181
+
182
+ if file_path.suffix.lower() not in supported_extensions:
183
+ continue
184
+
185
+ if any(part.startswith(".") for part in file_path.parts):
186
+ continue
187
+
188
+ try:
189
+ text = ""
190
 
191
+ if file_path.suffix.lower() == ".pdf":
192
+ reader = PdfReader(str(file_path))
193
+
194
+ pages = []
195
+ for page in reader.pages:
196
+ pages.append(page.extract_text() or "")
197
+
198
+ text = "\n".join(pages)
199
+
200
+ else:
201
+ text = file_path.read_text(
202
+ encoding="utf-8",
203
+ errors="ignore"
204
+ )
205
+
206
+ for index, chunk in enumerate(split_into_chunks(text)):
207
+ documents.append({
208
+ "source": str(file_path.relative_to(DATA_ROOT)),
209
+ "chunk": index + 1,
210
+ "content": chunk
211
+ })
212
+
213
+ except Exception as exc:
214
+ print(f"Could not read document {file_path}: {exc}")
215
+
216
+ print(f"Loaded {len(documents)} document chunks.")
217
+ return documents
218
+
219
+
220
+ # Load files once when the Space starts.
221
+ CSV_RECORDS = load_csv_records()
222
+ DOCUMENTS = load_documents()
223
+
224
+
225
+ # --------------------------------------------------
226
+ # RETRIEVE RELEVANT INFORMATION
227
+ # --------------------------------------------------
228
+
229
+ def retrieve_context(query):
230
+ context_parts = []
231
+
232
+ # Search startup database
233
+ scored_records = []
234
+
235
+ for record in CSV_RECORDS:
236
+ score = score_text(query, record["content"])
237
+
238
+ if score > 0:
239
+ scored_records.append((score, record))
240
+
241
+ scored_records.sort(key=lambda x: x[0], reverse=True)
242
+
243
+ for score, record in scored_records[:MAX_CSV_RESULTS]:
244
+ context_parts.append(
245
+ f"""
246
+ INTERNAL DATABASE RECORD
247
+ Source: {record['source']}
248
+ Row: {record['row']}
249
+ {record['content']}
250
+ """
251
+ )
252
+
253
+ # Search knowledge documents
254
+ scored_documents = []
255
+
256
+ for document in DOCUMENTS:
257
+ searchable_text = (
258
+ document["source"] + "\n" + document["content"]
259
+ )
260
+
261
+ score = score_text(query, searchable_text)
262
+
263
+ if score > 0:
264
+ scored_documents.append((score, document))
265
+
266
+ scored_documents.sort(key=lambda x: x[0], reverse=True)
267
+
268
+ for score, document in scored_documents[:MAX_DOCUMENT_RESULTS]:
269
+ context_parts.append(
270
+ f"""
271
+ KNOWLEDGE DOCUMENT
272
+ Source: {document['source']}
273
+ Section: {document['chunk']}
274
+ {document['content']}
275
+ """
276
+ )
277
+
278
+ if not context_parts:
279
+ return (
280
+ "No directly relevant information was found in the "
281
+ "currently loaded NBV files."
282
+ )
283
+
284
+ combined = "\n".join(context_parts)
285
+
286
+ return combined[:MAX_CONTEXT_CHARS]
287
+
288
+
289
+ # --------------------------------------------------
290
+ # GEMINI CHAT
291
+ # --------------------------------------------------
292
 
293
  def respond(
294
  message,
295
+ history: list[dict],
296
  system_message,
297
  max_tokens,
298
  temperature,
299
  top_p,
300
  ):
 
 
 
 
 
301
  api_key = os.getenv("GEMINI_API_KEY")
302
+
303
  if not api_key:
304
  yield (
305
  "Configuration error: GEMINI_API_KEY is missing. "
306
+ "Add it under Hugging Face Space Settings → Secrets."
 
307
  )
308
  return
309
 
310
+ try:
311
+ client = genai.Client(api_key=api_key)
312
+
313
+ # Retrieve relevant NBV information before calling Gemini.
314
+ retrieved_context = retrieve_context(message)
315
 
316
+ final_system_instruction = f"""
317
+ {NBV_INSTRUCTIONS}
 
 
 
318
 
319
+ Additional instructions:
320
+ {system_message or "Follow the NBV research instructions."}
321
+
322
+ RETRIEVED INTERNAL KNOWLEDGE:
323
+ {retrieved_context}
324
+
325
+ Use the retrieved knowledge when relevant.
326
+ If no relevant information was found, do not pretend that you
327
+ searched or found an internal record.
328
+ """
329
+
330
+ contents = []
331
+
332
+ for item in history or []:
333
+ role = item.get("role")
334
+ content = item.get("content")
335
+
336
+ if not isinstance(content, str) or not content.strip():
337
+ continue
338
 
339
+ if role == "user":
340
+ contents.append(
341
+ types.Content(
342
+ role="user",
343
+ parts=[types.Part.from_text(text=content)]
344
+ )
345
  )
346
+
347
+ elif role == "assistant":
348
+ contents.append(
349
+ types.Content(
350
+ role="model",
351
+ parts=[types.Part.from_text(text=content)]
352
+ )
353
  )
354
+
355
+ contents.append(
356
+ types.Content(
357
+ role="user",
358
+ parts=[types.Part.from_text(text=message)]
359
  )
360
+ )
361
 
362
+ config = types.GenerateContentConfig(
363
+ system_instruction=final_system_instruction,
364
+ max_output_tokens=int(max_tokens),
365
+ temperature=float(temperature),
366
+ top_p=float(top_p),
367
  )
 
368
 
369
+ answer = ""
 
 
 
 
 
370
 
 
 
371
  for chunk in client.models.generate_content_stream(
372
  model=MODEL_NAME,
373
  contents=contents,
 
381
  yield "I couldn't generate a response. Please try again."
382
 
383
  except Exception as exc:
 
384
  print(f"Gemini API error: {type(exc).__name__}: {exc}")
385
+
386
  yield (
387
  "Sorry, the AI service couldn't complete your request. "
388
+ "Please check the Space logs and Gemini API quota."
 
389
  )
390
 
391
 
392
+ # --------------------------------------------------
393
+ # GRADIO INTERFACE
394
+ # --------------------------------------------------
395
+
396
  chatbot = gr.ChatInterface(
397
  fn=respond,
398
  additional_inputs=[
399
+ gr.Textbox(
400
+ value="Answer using the NBV investment research instructions.",
401
+ label="Additional instructions"
402
+ ),
403
  gr.Slider(
404
  minimum=1,
405
  maximum=2048,
406
+ value=1024,
407
  step=1,
408
+ label="Max new tokens"
409
  ),
410
  gr.Slider(
411
  minimum=0.1,
412
  maximum=2.0,
413
+ value=0.5,
414
  step=0.1,
415
+ label="Temperature"
416
  ),
417
  gr.Slider(
418
  minimum=0.1,
419
  maximum=1.0,
420
  value=0.95,
421
  step=0.05,
422
+ label="Top-p"
423
  ),
424
  ],
425
+ title="NBV Investment Research Assistant",
426
+ description=(
427
+ "Ask questions about NBV's investment thesis, startup "
428
+ "pipeline, cohorts and company research."
429
+ )
430
  )
431
 
432
+
433
  if __name__ == "__main__":
434
  chatbot.launch()
435
+