Untitled

mail@pastecode.io avatar
unknown
python
a year ago
5.5 kB
4
Indexable
Never
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow 
from datetime import datetime
import requests
import os
import json 
import redis 
import threading 
import time
from flask_mongoengine import MongoEngine
import mongoengine as me
from bson.objectid import ObjectId
from dotenv import load_dotenv
from AI.openaiutil import *
from cache import *
import firebase_admin
from firebase_admin import credentials, firestore

load_dotenv()


GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
MONGO_CLUSTER = os.getenv("MONGO_CLUSTER")


GOOGLE_NEARBY_SEARCH = "https://maps.googleapis.com/maps/api/place/nearbysearch/json"
# Init app
app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {
    'host': MONGO_CLUSTER
}
#db = MongoEngine(app)


# Initialize Firebase
cred = credentials.Certificate("./conciergebackburhan-firebase-adminsdk-8mn6k-4dbcc1b501.json")
firebase_admin.initialize_app(cred)

# Get a reference to the Firestore service
db = firestore.client()

# Listen for changes to the user's data
users_ref = db.collection('users')

#Trying to see what changed in the document. THis is copied from chatgpt and is wrong. TODO: Need to see how to implement this correctly
for user_id in ['John Doe', 'Jane Doe', 'Alice', 'Bob']:
    doc_ref = users_ref.document(user_id)
    doc_watch = doc_ref.on_snapshot(lambda doc_snapshot, changes, read_time: 
        [actions[change.field.path](user_id) for change in changes if change.field.path in actions]
    )


"""
class Itinerary(db.EmbeddedDocument):
    city = db.StringField(required=True)
    latitude = db.StringField()
    longitude = db.StringField()
    currentItinerary = db.BooleanField()
    googleAttractionPlace_id = db.ListField()
    googleFoodPlace_id = db.ListField()

class User(me.Document):
    name = me.StringField(required=True)
    cuisine = me.ListField()
    attractionType = me.ListField()
    userCatagory = me.ListField()
    itinerary = me.EmbeddedDocumentField(Itinerary)
"""

def get_nearby_places(userRequest):
   headers = {}
   response = requests.get(GOOGLE_NEARBY_SEARCH, params=userRequest)
   print(response.url)
   print(response.text)
   places = json.loads(response.text)['results']
   return places

def getLatLong(city):
   if city == "NewYork":
      return ("40.7831","-73.9712")

messages = []
@app.route('/customerInput/start', methods=['POST'])
def primeTheModel():
  messages.append({"role": "system", "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous."})
  messages.append({"role": "user", "content": "Create a 3 day itinerary including hiking"})
  chat_response = chat_completion_request(
      messages, functions=functions
  )
  assistant_message = chat_response.json()["choices"][0]["message"]
  messages.append(assistant_message)
  pretty_print_conversation(messages)

  messages.append({"role": "user", "content": "Create it for New York city"})
  chat_response = chat_completion_request(
      messages, functions=functions
  )
  assistant_message = chat_response.json()["choices"][0]["message"]
  messages.append(assistant_message)
  pretty_print_conversation(messages)
  return 'Primed successfully!', 200


@app.route('/customerInput', methods=['POST'])
def openAIParseText():
  customerText = request.json['data']
  user_id = request.json['user_id']
  print(customerText)

  messages.append({"role": "user", "content": customerText})
  chat_response = chat_completion_request(
      messages, functions=functions
  )
  assistant_message = chat_response.json()["choices"][0]["message"]
  messages.append(assistant_message)
  pretty_print_conversation(messages)

  parsed_data = assistant_message['function_call']
  parsedKV = parsed_data["arguments"]
  #this is an encoded json string
  print(parsedKV)
  #convert to a json string
  parsedKVJsonStr = json.dumps(parsedKV)
  print(parsedKVJsonStr)
 #need to do json.loads twice to convert it to a dictionary. 
  parsedKVObj = json.loads(json.loads(parsedKVJsonStr))
  doc_ref = db.collection('users').document(user_id)
  doc_ref.set(parsedKVObj)
  
  return 'User updated successfully!', 200
 # nearbyPlaces = get_nearby_places(userRequest)

# Get All Products
@app.route('/itinerary', methods=['POST'])
def get_itinerary():
  attractionCatagory = request.json['attractionCatagory']
  foodCatagory = request.json['foodCatagory']
  name = request.json['username']
  userCatagory = request.json['userCatagory']
  city = request.json['city']

  user = User(name = name)
  user.attractionType.extend(attractionCatagory)
  user.cuisine.extend(foodCatagory)
  user.userCatagory.extend(userCatagory)

  latLong = getLatLong(city)
  itinerary = Itinerary(city = city, latitude =latLong[0], longitude=latLong[1])
  user.itinerary = itinerary

  for cuisine in user.cuisine:
    userRequest = {
      'location': ",".join(latLong),
        'key': GOOGLE_API_KEY,
        'keyword': cuisine,
        'type': "restaurant",
        'radius': 1500,
        'minprice': 3,
        }
    nearbyPlaces = get_nearby_places(userRequest)
    for place in nearbyPlaces:
      itinerary.googleFoodPlace_id.append(place["place_id"])

  user.save()
  return '<div>Hello</div>'


# Run Server
if __name__ == '__main__':
  app.run(debug=True)