Abdulla Fahem commited on
Commit
87d17b6
·
1 Parent(s): ef0c77d

Update application file

Browse files
Files changed (2) hide show
  1. app.py +41 -66
  2. requirements.txt +2 -1
app.py CHANGED
@@ -16,6 +16,7 @@ from torch.utils.data import Dataset
16
  from datetime import datetime
17
  import numpy as np
18
  from random import choice
 
19
 
20
  class TravelDataset(Dataset):
21
  def __init__(self, data, tokenizer, max_length=512):
@@ -335,91 +336,65 @@ def generate_fallback_plan(destination, days, interests, budget):
335
  return format_travel_plan(fallback_plan, days)
336
 
337
  def format_travel_plan(plan, days):
338
- """Format the travel plan with improved readability and structure"""
339
- formatted_plan = []
340
- day_sections = []
341
- current_day = None
342
- current_activities = []
 
343
 
344
- # Process the plan line by line
 
345
  for line in plan.split('\n'):
346
  line = line.strip()
347
  if not line:
348
  continue
349
-
350
- # Check for day headers
351
  if line.lower().startswith('day'):
352
- # Save previous day's activities if they exist
353
- if current_day is not None and current_activities:
354
- # Only add days that are within the requested range
355
- if current_day <= days:
356
- day_sections.append({
357
- 'day': current_day,
358
- 'activities': current_activities
359
- })
360
-
361
- # Extract day number
362
  try:
363
- day_part = line.split(':', 1)
364
- day_num = int(''.join(filter(str.isdigit, day_part[0])))
365
- # Only process days within the requested range
366
- if day_num <= days:
367
  current_day = day_num
368
- current_activities = []
369
-
370
- # Process content after the day header if it exists
371
- if len(day_part) > 1:
372
- # Split activities by periods and filter out empty ones
373
- activities = [act.strip() for act in day_part[1].split('.') if act.strip()]
374
- current_activities.extend(activities)
375
-
376
  except ValueError:
 
377
  continue
378
- elif current_day is not None and current_day <= days:
379
- # Only add activities for days within the requested range
380
- # Split the line by periods to separate activities
381
- activities = [act.strip() for act in line.split('.') if act.strip()]
382
- current_activities.extend(activities)
383
-
384
- # Add the last day if there are pending activities and within range
385
- if current_day is not None and current_activities and current_day <= days:
386
- day_sections.append({
387
- 'day': current_day,
388
- 'activities': current_activities
389
- })
 
 
390
 
391
- # Sort days and ensure we have exactly the requested number of days
392
- day_sections.sort(key=lambda x: x['day'])
 
 
 
 
 
393
 
394
- # Generate the final formatted plan
 
395
  for day in range(1, days + 1):
396
- # Find the matching day's activities or use a placeholder
397
- day_content = next(
398
- (section for section in day_sections if section['day'] == day),
399
- {'day': day, 'activities': []}
400
- )
401
-
402
- # Format the day's content with markdown
403
  formatted_plan.append(f"### Day {day}\n")
404
 
405
- # If no activities found for this day, add default activity
406
- if not day_content['activities']:
407
- formatted_plan.append("- Explore local attractions and sights")
408
- else:
409
- # Format each activity with bullet points
410
- for activity in day_content['activities']:
411
- # Clean up the activity text
412
- activity = activity.strip()
413
- if activity.lower().startswith('optional'):
414
- formatted_plan.append(f"- *{activity}*")
415
- else:
416
- formatted_plan.append(f"- {activity}")
417
-
418
- # Add spacing between days
419
  formatted_plan.append("\n")
420
 
421
  return "\n".join(formatted_plan)
422
 
 
423
  def main():
424
  st.set_page_config(
425
  page_title="AI Travel Planner",
 
16
  from datetime import datetime
17
  import numpy as np
18
  from random import choice
19
+ import re
20
 
21
  class TravelDataset(Dataset):
22
  def __init__(self, data, tokenizer, max_length=512):
 
336
  return format_travel_plan(fallback_plan, days)
337
 
338
  def format_travel_plan(plan, days):
339
+ """Format travel plan for 1-14 days with flexible activity distribution"""
340
+ # Validate days input
341
+ days = max(1, min(days, 14))
342
+
343
+ # Initialize day activities dictionary
344
+ day_activities = {day: [] for day in range(1, days + 1)}
345
 
346
+ # Parse input plan
347
+ current_day = None
348
  for line in plan.split('\n'):
349
  line = line.strip()
350
  if not line:
351
  continue
352
+
353
+ # Detect day headers
354
  if line.lower().startswith('day'):
 
 
 
 
 
 
 
 
 
 
355
  try:
356
+ day_num = int(''.join(filter(str.isdigit, line.split()[0])))
357
+ if 1 <= day_num <= days:
 
 
358
  current_day = day_num
 
 
 
 
 
 
 
 
359
  except ValueError:
360
+ current_day = None
361
  continue
362
+
363
+ # Collect activities
364
+ elif current_day and current_day <= days:
365
+ # Split by multiple delimiters, filter meaningful activities
366
+ activities = [
367
+ act.strip()
368
+ for act in re.split(r'[.;,]', line)
369
+ if act.strip() and len(act.strip()) > 5
370
+ ]
371
+
372
+ # Add activities for current day
373
+ for activity in activities:
374
+ if len(day_activities[current_day]) < 4:
375
+ day_activities[current_day].append(activity)
376
 
377
+ # Ensure each day has activities
378
+ for day in range(1, days + 1):
379
+ if not day_activities[day]:
380
+ if day == 1:
381
+ day_activities[day].append("Explore city highlights")
382
+ else:
383
+ day_activities[day].append("Continue exploring local attractions")
384
 
385
+ # Generate formatted plan
386
+ formatted_plan = []
387
  for day in range(1, days + 1):
 
 
 
 
 
 
 
388
  formatted_plan.append(f"### Day {day}\n")
389
 
390
+ for activity in day_activities[day]:
391
+ formatted_plan.append(f"- {activity}")
392
+
 
 
 
 
 
 
 
 
 
 
 
393
  formatted_plan.append("\n")
394
 
395
  return "\n".join(formatted_plan)
396
 
397
+
398
  def main():
399
  st.set_page_config(
400
  page_title="AI Travel Planner",
requirements.txt CHANGED
@@ -6,4 +6,5 @@ accelerate
6
  sentencepiece
7
  protobuf
8
  typing-extensions
9
- packaging
 
 
6
  sentencepiece
7
  protobuf
8
  typing-extensions
9
+ packaging
10
+ re