Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Bebdyshev/backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Travel AI Planner Backend

An AI-powered travel planning backend with chatbot capabilities for finding flights, hotels, restaurants, and activities. Built with FastAPI, LangChain, and Groq AI.

Features

  • AI Travel Assistant: Chat with an intelligent bot that helps plan your trips
  • Flight Search: Find and compare flights between destinations
  • Hotel Booking: Search hotels with filters for dates, price range, and amenities
  • Restaurant Recommendations: Discover restaurants by cuisine, price, and dietary needs
  • Activity & Attraction Search: Find tours, activities, and tourist attractions
  • User Authentication: Secure user registration and login system
  • Conversation History: Save and retrieve past travel planning conversations

Tech Stack

  • Backend: FastAPI
  • AI/LLM: Groq AI with LangChain
  • Database: PostgreSQL with SQLAlchemy
  • Authentication: JWT tokens
  • Web Scraping: Selenium (for flight data)
  • Search: Serper API for web search

API Endpoints

Authentication

  • POST /auth/register - Register new user
  • POST /auth/login - User login
  • POST /auth/refresh - Refresh access token

Travel Chat

  • POST /chat/ - Chat with AI travel assistant
  • GET /chat/conversations - Get user's conversations
  • GET /chat/conversation/{id} - Get specific conversation

User Management

  • GET /users/me - Get current user profile
  • PUT /users/me - Update user profile

Environment Variables

Create a .env file with the following variables:

# Database
DATABASE_URL=postgresql://username:password@localhost:5432/travel_planner

# JWT Authentication
SECRET_KEY=your-secret-key-here
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

# AI/LLM Configuration
GROQ_API_KEY=your-groq-api-key
GROQ_DEFAULT_MODEL=meta-llama/llama-4-maverick-17b-128e-instruct
LLM_TEMPERATURE=0.7

# Search API
SERPER_API_KEY=your-serper-api-key

# Chat Configuration
CHAT_CONTEXT_MESSAGES=20

Installation & Setup

  1. Clone the repository
git clone <repository-url>
cd travel-ai-planner
  1. Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
  1. Install dependencies

    pip install -r requirements.txt
  2. Set up database

# Create PostgreSQL database
# Update DATABASE_URL in .env file
  1. Run the application
    uvicorn src.app:app --reload

The API will be available at http://localhost:8000

Usage Examples

Chat with Travel Assistant

import requests

# Start a conversation
response = requests.post("http://localhost:8000/chat/", json={
    "messages": [
        {"role": "user", "content": "I want to plan a trip to Paris for 3 days"}
    ]
}, headers={"Authorization": "Bearer YOUR_TOKEN"})

print(response.json())

Search Hotels

The AI assistant can search for hotels when you ask:

  • "Find hotels in Paris for March 15-18"
  • "Show me budget hotels in Tokyo"
  • "I need a luxury hotel in New York with a spa"

Find Restaurants

Ask the assistant about dining:

  • "Recommend Italian restaurants in Rome"
  • "Find vegan restaurants in Berlin"
  • "What are the best local restaurants in Barcelona?"

Plan Activities

Get activity suggestions:

  • "What activities can I do in London?"
  • "Find cultural tours in Paris"
  • "Show me outdoor activities in Colorado"

Development

Project Structure

src/
├── ai/
│   ├── tools/          # Travel search tools
│   ├── agent.py        # AI agent configuration
│   └── conversation.py # Conversation management
├── routes/             # API endpoints
├── schemas/           # Database models
├── app.py            # FastAPI application
├── config.py         # Database configuration
└── auth_utils.py     # Authentication utilities

Adding New Travel Tools

  1. Create a new tool in src/ai/tools/
  2. Import and add to tools list in src/ai/agent.py
  3. Update the system prompt to describe the new tool

API Documentation

Once running, visit:

  • Swagger UI: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

License

This project is licensed under the MIT License.

TripAdvisor Restaurant Scraper

A Python tool to extract restaurant data from TripAdvisor using both GraphQL API and HTML parsing.

Features

  • 🔍 Location Search: Find restaurant listing URLs using TripAdvisor's GraphQL API
  • 🍽️ Restaurant Parsing: Extract detailed restaurant data from HTML listings
  • 📊 Rich Data Extraction: Get ratings, reviews, cuisine types, prices, and more
  • 💾 Data Export: Save results to JSON files
  • 🏆 Special Badges: Detect Travelers' Choice awards and sponsored listings

Installation

pip install requests beautifulsoup4 lxml

Usage

Basic Usage

from test import TripAdvisorRestaurantAPI

api = TripAdvisorRestaurantAPI()

# Get restaurant URL for a city
search_results = api.search_locations("London")
restaurants_url = api.extract_restaurant_url(search_results)

# Parse restaurants from the URL
restaurants = api.get_restaurants_from_url(restaurants_url)

print(f"Found {len(restaurants)} restaurants")
for restaurant in restaurants:
    print(f"{restaurant['name']} - {restaurant['rating']}★")

Parse HTML Content Directly

# If you have HTML content from a TripAdvisor restaurant listing page
html_content = """<your HTML content here>"""
restaurants = api.parse_restaurant_listings_html(html_content)

Run the Complete Demo

python test.py

This will:

  1. Search for London restaurants
  2. Get the restaurant listing URL
  3. Fetch and parse all restaurants
  4. Display the first 5 restaurants
  5. Save all data to JSON files

Extracted Data

For each restaurant, the tool extracts:

  • Name: Restaurant name
  • Rating: Numerical rating (e.g., 4.5)
  • Review Count: Number of reviews
  • Cuisine Types: List of cuisine categories
  • Price Range: Price level (e.g., "$$ - $$$")
  • Status: "open" or "closed"
  • URL: Full TripAdvisor restaurant page URL
  • Travelers Choice 2024: Boolean flag
  • Sponsored: Boolean flag for sponsored listings

Example Output

{
  "name": "Bustronome London",
  "rating": 4.9,
  "review_count": 580,
  "cuisine_types": ["French", "European"],
  "price_range": "$$$$",
  "status": "open",
  "url": "https://www.tripadvisor.com/Restaurant_Review-g186338-d19260282...",
  "travelers_choice_2024": true,
  "sponsored": true
}

Files Generated

  • restaurants_url_<city>_<timestamp>.json: Restaurant listing URL
  • restaurants_data_<city>_<timestamp>.json: All restaurant data
  • all_urls_<city>_<timestamp>.json: All available TripAdvisor URLs

Testing

Test with a specific HTML snippet:

python test_html_parsing.py

Notes

  • The tool respects TripAdvisor's structure and uses appropriate headers
  • Rate limiting is handled automatically
  • Error handling for missing elements
  • Supports multiple cities and locations

Dependencies

  • requests: HTTP requests
  • beautifulsoup4: HTML parsing
  • lxml: XML/HTML parser (faster)
  • re: Regular expressions
  • json: JSON handling
  • time: Timestamps
  • logging: Logging functionality

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published