Amrith2k6 commited on
Commit
aab8d2e
Β·
verified Β·
1 Parent(s): 0109c0e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -167
app.py CHANGED
@@ -1,5 +1,5 @@
1
  """
2
- IT-Business Analysis Assistant - Professional Version
3
  """
4
 
5
  import os
@@ -29,7 +29,7 @@ class Config:
29
  BASE_DIR = Path(__file__).resolve().parent
30
  DATA_DIR = BASE_DIR / "data"
31
  KEYWORDS_FILE = DATA_DIR / "ba_keywords.json"
32
- KEYWORD_MATCH_THRESHOLD = 0.7 # Lowered for better matching
33
 
34
  APP_NAME = "Professional IT Business Analysis Assistant"
35
  APP_VERSION = "3.0.0"
@@ -41,14 +41,46 @@ class Config:
41
  DEEPSEEK_MODEL = "deepseek-chat"
42
 
43
  # ---------------------------
44
- # Initialize DeepSeek
45
  # ---------------------------
46
  DEEPSEEK_AVAILABLE = False
47
- if Config.DEEPSEEK_API_KEY and len(Config.DEEPSEEK_API_KEY) > 10:
48
- DEEPSEEK_AVAILABLE = True
49
- logger.info("βœ… DeepSeek API configured - FREE TIER ACTIVE")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  else:
51
- logger.info("πŸ“š Using local templates only")
 
52
 
53
  # ---------------------------
54
  # Load BA Keywords
@@ -73,7 +105,7 @@ def get_default_ba_keywords() -> Dict[str, List[str]]:
73
  "Core Concepts": [
74
  "business analysis", "requirements gathering", "stakeholder analysis",
75
  "business case", "scope definition", "gap analysis", "requirements",
76
- "stakeholder", "business need", "value proposition"
77
  ],
78
  "Methodologies": [
79
  "agile", "scrum", "kanban", "waterfall", "babok", "bpmn", "uml",
@@ -114,11 +146,10 @@ def is_ba_related(question: str) -> Tuple[bool, List[str], List[str]]:
114
  matched_keywords = []
115
  matched_categories = set()
116
 
117
- # Simple contains check - no fuzzy matching needed
118
  for keyword in ALL_KEYWORDS:
119
  if keyword in question_lower:
120
  matched_keywords.append(keyword)
121
- # Find category
122
  for cat, keys in BA_KEYWORDS.items():
123
  if any(k.lower() == keyword for k in keys):
124
  matched_categories.add(cat)
@@ -126,13 +157,14 @@ def is_ba_related(question: str) -> Tuple[bool, List[str], List[str]]:
126
 
127
  # Also check individual words for common BA terms
128
  words = question_lower.split()
129
- ba_terms = ["stakeholder", "requirement", "agile", "scrum", "babok", "banking", "healthcare"]
 
130
  for term in ba_terms:
131
  if term in words or term in question_lower:
132
  matched_keywords.append(term)
133
- if term == "stakeholder":
134
  matched_categories.add("Core Concepts")
135
- elif term in ["agile", "scrum", "babok"]:
136
  matched_categories.add("Methodologies")
137
  elif term in ["banking", "healthcare"]:
138
  matched_categories.add("Business Domains")
@@ -141,15 +173,18 @@ def is_ba_related(question: str) -> Tuple[bool, List[str], List[str]]:
141
  return is_related, list(set(matched_keywords))[:5], list(matched_categories)
142
 
143
  # ---------------------------
144
- # Get DeepSeek Response
145
  # ---------------------------
146
  def get_deepseek_response(question: str) -> Optional[str]:
147
  """Get response from DeepSeek API"""
148
 
149
  if not DEEPSEEK_AVAILABLE:
 
150
  return None
151
 
152
  try:
 
 
153
  url = f"{Config.DEEPSEEK_BASE_URL}/chat/completions"
154
  headers = {
155
  "Authorization": f"Bearer {Config.DEEPSEEK_API_KEY}",
@@ -166,161 +201,52 @@ def get_deepseek_response(question: str) -> Optional[str]:
166
  }
167
 
168
  response = requests.post(url, headers=headers, json=payload, timeout=30)
169
- response.raise_for_status()
 
 
 
 
170
  result = response.json()
 
171
  return result["choices"][0]["message"]["content"]
172
 
 
 
 
 
 
 
173
  except Exception as e:
174
- logger.warning(f"DeepSeek API error: {e}")
175
  return None
176
 
177
  # ---------------------------
178
- # Local Response
179
  # ---------------------------
180
  def get_local_response(question: str, keywords: List[str], categories: List[str]) -> str:
181
  """Get response from local templates"""
 
 
182
 
183
  question_lower = question.lower()
184
 
185
- # Check for common topics
186
- if "stakeholder" in question_lower:
187
- return """
188
- ## πŸ‘₯ Stakeholder Management
189
-
190
- ### Key Concepts
191
- - **Stakeholder Identification**: Find all people affected by your project
192
- - **Stakeholder Analysis**: Assess power, interest, and influence
193
- - **Engagement Strategies**: Communicate appropriately with each group
194
-
195
- ### Power-Interest Grid
196
- - **High Power, High Interest**: Manage closely (sponsors, key customers)
197
- - **High Power, Low Interest**: Keep satisfied (executives, regulators)
198
- - **Low Power, High Interest**: Keep informed (end users, SMEs)
199
- - **Low Power, Low Interest**: Monitor (general staff)
200
-
201
- ### RACI Matrix
202
- - **R** = Responsible (does the work)
203
- - **A** = Accountable (approves)
204
- - **C** = Consulted (provides input)
205
- - **I** = Informed (receives updates)
206
-
207
- ### Quick Tips
208
- 1. Identify stakeholders early
209
- 2. Understand their motivations
210
- 3. Communicate regularly
211
- 4. Manage expectations
212
- 5. Build relationships
213
- """
214
 
215
- elif "requirement" in question_lower or "gathering" in question_lower:
216
- return """
217
- ## πŸ“ Requirements Gathering
218
-
219
- ### Elicitation Techniques
220
- - **Interviews**: One-on-one discussions with stakeholders
221
- - **Workshops**: Collaborative sessions with multiple stakeholders
222
- - **Surveys**: Collect feedback from large groups
223
- - **Observation**: Watch users in their environment
224
- - **Document Analysis**: Review existing documentation
225
-
226
- ### Types of Requirements
227
- 1. **Business Requirements**: High-level organizational needs
228
- 2. **User Requirements**: What users need to do
229
- 3. **Functional Requirements**: What the system must do
230
- 4. **Non-Functional Requirements**: Performance, security, usability
231
-
232
- ### Best Practices
233
- - Ask open-ended questions
234
- - Listen actively
235
- - Validate understanding
236
- - Document clearly
237
- - Get sign-off
238
- """
239
 
240
- elif "agile" in question_lower or "scrum" in question_lower:
241
- return """
242
- ## πŸ”„ Agile Methodology
243
-
244
- ### Agile Principles
245
- - Individuals and interactions over processes and tools
246
- - Working software over comprehensive documentation
247
- - Customer collaboration over contract negotiation
248
- - Responding to change over following a plan
249
-
250
- ### Scrum Framework
251
- - **Roles**: Product Owner, Scrum Master, Development Team
252
- - **Events**: Sprint Planning, Daily Stand-up, Sprint Review, Retrospective
253
- - **Artifacts**: Product Backlog, Sprint Backlog, Increment
254
-
255
- ### Key Concepts
256
- - **User Stories**: "As a [user], I want [feature] so that [benefit]"
257
- - **Acceptance Criteria**: Conditions that must be met
258
- - **Definition of Done**: Team's agreement on completion
259
- """
260
-
261
- elif "banking" in question_lower or "financial" in question_lower:
262
- return """
263
- ## 🏦 Banking & Financial Services
264
-
265
- ### Key Regulations
266
- - **Basel III/IV**: Capital adequacy, risk management
267
- - **SOX**: Internal controls, audit trails
268
- - **PSD2/Open Banking**: API requirements, customer data access
269
-
270
- ### Common Projects
271
- - Core banking transformation
272
- - Payment systems
273
- - Mobile banking apps
274
- - Regulatory reporting
275
-
276
- ### BA Considerations
277
- - Security and compliance are critical
278
- - Real-time processing requirements
279
- - Complex integration with legacy systems
280
- """
281
-
282
- elif "healthcare" in question_lower or "hipaa" in question_lower:
283
- return """
284
- ## πŸ₯ Healthcare IT
285
-
286
- ### Key Regulations
287
- - **HIPAA**: Privacy, security, patient data
288
- - **FDA**: Medical device software validation
289
- - **HL7/FHIR**: Healthcare data interoperability
290
-
291
- ### Common Projects
292
- - Electronic Health Records (EHR)
293
- - Telemedicine platforms
294
- - Medical devices
295
- - Clinical trials management
296
-
297
- ### BA Considerations
298
- - Patient safety is paramount
299
- - Strict compliance requirements
300
- - Complex clinical workflows
301
- - Interoperability standards
302
- """
303
-
304
- else:
305
- categories_str = ', '.join(categories) if categories else 'General BA'
306
- keywords_str = ', '.join(keywords) if keywords else 'business analysis'
307
-
308
- return f"""
309
  ## πŸ“Š Business Analysis Information
310
 
311
- **Categories:** {categories_str}
312
- **Topics:** {keywords_str}
313
 
314
  ### Quick Reference
315
  - **Core Concepts**: Requirements, stakeholders, scope, value
316
  - **Methodologies**: Agile, Scrum, Waterfall, BABOK
317
  - **Domains**: Banking, Healthcare, Retail, Supply Chain
318
-
319
- ### Ask About
320
- - Specific techniques (traceability, prioritization)
321
- - Industry domains (banking, healthcare)
322
- - Methodologies (Agile, BABOK)
323
- - Best practices (stakeholder management, requirements)
324
  """
325
 
326
  # ---------------------------
@@ -341,33 +267,21 @@ def ask_ba_assistant(question: str) -> str:
341
  return """❌ I specialize in IT-Business Analysis topics only.
342
 
343
  ### βœ… Try Asking About:
344
-
345
- **Core Concepts**
346
  β€’ What is requirements gathering?
347
  β€’ How to manage stakeholders?
348
- β€’ What is a business case?
349
-
350
- **Methodologies**
351
  β€’ Explain Agile methodology
352
- β€’ What is Scrum?
353
- β€’ What is BABOK?
354
-
355
- **Business Domains**
356
- β€’ Banking and financial services
357
- β€’ Healthcare IT and HIPAA
358
- β€’ Retail and e-commerce
359
-
360
- **Specific Topics**
361
- β€’ Requirements traceability
362
- β€’ Stakeholder analysis
363
- β€’ User stories
364
  """
365
 
366
  # Try DeepSeek if available
367
  if DEEPSEEK_AVAILABLE:
 
368
  ai_response = get_deepseek_response(question)
369
  if ai_response:
370
  return ai_response + "\n\n---\n*Powered by DeepSeek AI Free Tier*"
 
 
371
 
372
  # Fallback to local templates
373
  response = get_local_response(question, keywords, categories)
@@ -379,7 +293,12 @@ def ask_ba_assistant(question: str) -> str:
379
  def build_app():
380
  """Build the Gradio interface"""
381
 
382
- status = "🟒 DEEPSEEK AI" if DEEPSEEK_AVAILABLE else "🟑 LOCAL TEMPLATES"
 
 
 
 
 
383
 
384
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
385
  gr.Markdown(f"""
@@ -387,6 +306,7 @@ def build_app():
387
  <h1>πŸ“Š Professional IT Business Analysis Assistant</h1>
388
  <p><i>AI-powered guide for BA concepts and business domains</i></p>
389
  <p>Version 3.0.0 | Mode: {status}</p>
 
390
  </div>
391
  """)
392
 
@@ -394,7 +314,7 @@ def build_app():
394
  with gr.Column(scale=2):
395
  question = gr.Textbox(
396
  label="Ask your BA question",
397
- placeholder="e.g., How to manage stakeholders? What is requirements traceability? Agile vs Waterfall?",
398
  lines=3
399
  )
400
  submit_btn = gr.Button("πŸ” Get Guidance", variant="primary")
@@ -413,7 +333,7 @@ def build_app():
413
  ["What is requirements traceability?"],
414
  ["Explain Agile methodology"],
415
  ["Banking domain analysis techniques"],
416
- ["HIPAA compliance requirements"]
417
  ],
418
  inputs=question
419
  )
 
1
  """
2
+ IT-Business Analysis Assistant - Professional Version with DeepSeek AI
3
  """
4
 
5
  import os
 
29
  BASE_DIR = Path(__file__).resolve().parent
30
  DATA_DIR = BASE_DIR / "data"
31
  KEYWORDS_FILE = DATA_DIR / "ba_keywords.json"
32
+ KEYWORD_MATCH_THRESHOLD = 0.7
33
 
34
  APP_NAME = "Professional IT Business Analysis Assistant"
35
  APP_VERSION = "3.0.0"
 
41
  DEEPSEEK_MODEL = "deepseek-chat"
42
 
43
  # ---------------------------
44
+ # Initialize DeepSeek with Better Validation
45
  # ---------------------------
46
  DEEPSEEK_AVAILABLE = False
47
+ DEEPSEEK_ERROR = None
48
+
49
+ if Config.DEEPSEEK_API_KEY:
50
+ logger.info(f"DeepSeek API key found (length: {len(Config.DEEPSEEK_API_KEY)})")
51
+
52
+ # Simple validation - key should be reasonably long
53
+ if len(Config.DEEPSEEK_API_KEY) > 10:
54
+ # Test the API key with a simple request
55
+ try:
56
+ headers = {
57
+ "Authorization": f"Bearer {Config.DEEPSEEK_API_KEY}",
58
+ "Content-Type": "application/json"
59
+ }
60
+
61
+ # Test the API by listing models (lightweight call)
62
+ test_response = requests.get(
63
+ f"{Config.DEEPSEEK_BASE_URL}/models",
64
+ headers=headers,
65
+ timeout=10
66
+ )
67
+
68
+ if test_response.status_code == 200:
69
+ DEEPSEEK_AVAILABLE = True
70
+ logger.info("βœ… DeepSeek API validated - FREE TIER ACTIVE")
71
+ logger.info(f"Available models: {test_response.json()}")
72
+ else:
73
+ DEEPSEEK_ERROR = f"API test failed with status {test_response.status_code}"
74
+ logger.warning(f"⚠️ {DEEPSEEK_ERROR}")
75
+ except Exception as e:
76
+ DEEPSEEK_ERROR = f"API connection error: {str(e)}"
77
+ logger.warning(f"⚠️ {DEEPSEEK_ERROR}")
78
+ else:
79
+ DEEPSEEK_ERROR = "API key too short (invalid format)"
80
+ logger.warning(f"⚠️ {DEEPSEEK_ERROR}")
81
  else:
82
+ DEEPSEEK_ERROR = "No API key found in environment"
83
+ logger.info("πŸ“š No DeepSeek API key - using local templates only")
84
 
85
  # ---------------------------
86
  # Load BA Keywords
 
105
  "Core Concepts": [
106
  "business analysis", "requirements gathering", "stakeholder analysis",
107
  "business case", "scope definition", "gap analysis", "requirements",
108
+ "stakeholder", "business need", "value proposition", "traceability"
109
  ],
110
  "Methodologies": [
111
  "agile", "scrum", "kanban", "waterfall", "babok", "bpmn", "uml",
 
146
  matched_keywords = []
147
  matched_categories = set()
148
 
149
+ # Simple contains check
150
  for keyword in ALL_KEYWORDS:
151
  if keyword in question_lower:
152
  matched_keywords.append(keyword)
 
153
  for cat, keys in BA_KEYWORDS.items():
154
  if any(k.lower() == keyword for k in keys):
155
  matched_categories.add(cat)
 
157
 
158
  # Also check individual words for common BA terms
159
  words = question_lower.split()
160
+ ba_terms = ["stakeholder", "requirement", "agile", "scrum", "babok",
161
+ "banking", "healthcare", "traceability", "waterfall", "kanban"]
162
  for term in ba_terms:
163
  if term in words or term in question_lower:
164
  matched_keywords.append(term)
165
+ if term in ["stakeholder", "requirement", "traceability"]:
166
  matched_categories.add("Core Concepts")
167
+ elif term in ["agile", "scrum", "babok", "waterfall", "kanban"]:
168
  matched_categories.add("Methodologies")
169
  elif term in ["banking", "healthcare"]:
170
  matched_categories.add("Business Domains")
 
173
  return is_related, list(set(matched_keywords))[:5], list(matched_categories)
174
 
175
  # ---------------------------
176
+ # Get DeepSeek Response with Better Error Handling
177
  # ---------------------------
178
  def get_deepseek_response(question: str) -> Optional[str]:
179
  """Get response from DeepSeek API"""
180
 
181
  if not DEEPSEEK_AVAILABLE:
182
+ logger.info("DeepSeek not available, skipping API call")
183
  return None
184
 
185
  try:
186
+ logger.info(f"Calling DeepSeek API for question: {question[:50]}...")
187
+
188
  url = f"{Config.DEEPSEEK_BASE_URL}/chat/completions"
189
  headers = {
190
  "Authorization": f"Bearer {Config.DEEPSEEK_API_KEY}",
 
201
  }
202
 
203
  response = requests.post(url, headers=headers, json=payload, timeout=30)
204
+
205
+ if response.status_code != 200:
206
+ logger.warning(f"DeepSeek API error: {response.status_code} - {response.text}")
207
+ return None
208
+
209
  result = response.json()
210
+ logger.info("βœ… DeepSeek API call successful")
211
  return result["choices"][0]["message"]["content"]
212
 
213
+ except requests.exceptions.Timeout:
214
+ logger.warning("DeepSeek API timeout")
215
+ return None
216
+ except requests.exceptions.ConnectionError:
217
+ logger.warning("DeepSeek API connection error")
218
+ return None
219
  except Exception as e:
220
+ logger.warning(f"DeepSeek API error: {type(e).__name__}: {e}")
221
  return None
222
 
223
  # ---------------------------
224
+ # Local Response Templates (Your existing templates)
225
  # ---------------------------
226
  def get_local_response(question: str, keywords: List[str], categories: List[str]) -> str:
227
  """Get response from local templates"""
228
+ # ... (keep your existing templates here - the ones I provided earlier)
229
+ # For brevity, I'm not copying all 200+ lines, but keep your enhanced templates
230
 
231
  question_lower = question.lower()
232
 
233
+ # Your existing template logic here...
234
+ if "agile" in question_lower and "scrum" not in question_lower:
235
+ return "## πŸ”„ Agile Methodology\n\n..." # Your agile template
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
+ # ... rest of your templates
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
 
239
+ # Default response
240
+ return f"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  ## πŸ“Š Business Analysis Information
242
 
243
+ **Categories:** {', '.join(categories) if categories else 'General BA'}
244
+ **Topics:** {', '.join(keywords) if keywords else 'business analysis'}
245
 
246
  ### Quick Reference
247
  - **Core Concepts**: Requirements, stakeholders, scope, value
248
  - **Methodologies**: Agile, Scrum, Waterfall, BABOK
249
  - **Domains**: Banking, Healthcare, Retail, Supply Chain
 
 
 
 
 
 
250
  """
251
 
252
  # ---------------------------
 
267
  return """❌ I specialize in IT-Business Analysis topics only.
268
 
269
  ### βœ… Try Asking About:
 
 
270
  β€’ What is requirements gathering?
271
  β€’ How to manage stakeholders?
 
 
 
272
  β€’ Explain Agile methodology
273
+ β€’ Banking domain analysis
274
+ β€’ Healthcare IT requirements
 
 
 
 
 
 
 
 
 
 
275
  """
276
 
277
  # Try DeepSeek if available
278
  if DEEPSEEK_AVAILABLE:
279
+ logger.info(f"Attempting DeepSeek for: {question}")
280
  ai_response = get_deepseek_response(question)
281
  if ai_response:
282
  return ai_response + "\n\n---\n*Powered by DeepSeek AI Free Tier*"
283
+ else:
284
+ logger.info("DeepSeek failed, falling back to local templates")
285
 
286
  # Fallback to local templates
287
  response = get_local_response(question, keywords, categories)
 
293
  def build_app():
294
  """Build the Gradio interface"""
295
 
296
+ if DEEPSEEK_AVAILABLE:
297
+ status = "🟒 DEEPSEEK AI ACTIVE"
298
+ status_detail = "Using DeepSeek Free Tier (5M tokens/month)"
299
+ else:
300
+ status = "🟑 LOCAL TEMPLATES"
301
+ status_detail = DEEPSEEK_ERROR if DEEPSEEK_ERROR else "No API key configured"
302
 
303
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
304
  gr.Markdown(f"""
 
306
  <h1>πŸ“Š Professional IT Business Analysis Assistant</h1>
307
  <p><i>AI-powered guide for BA concepts and business domains</i></p>
308
  <p>Version 3.0.0 | Mode: {status}</p>
309
+ <p style='font-size:0.9em; color:#666;'>{status_detail}</p>
310
  </div>
311
  """)
312
 
 
314
  with gr.Column(scale=2):
315
  question = gr.Textbox(
316
  label="Ask your BA question",
317
+ placeholder="e.g., How to manage stakeholders? What is requirements traceability?",
318
  lines=3
319
  )
320
  submit_btn = gr.Button("πŸ” Get Guidance", variant="primary")
 
333
  ["What is requirements traceability?"],
334
  ["Explain Agile methodology"],
335
  ["Banking domain analysis techniques"],
336
+ ["Healthcare compliance requirements"]
337
  ],
338
  inputs=question
339
  )