Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Week 1 Changes #128

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions functions/get-dealership.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const Cloudant = require('@cloudant/cloudant');
// Initialize Cloudant connection with IAM authentication
async function dbCloudantConnect() {
try {
const cloudant = Cloudant({
plugins: { iamauth: { iamApiKey: 'r6c5foCGS8FS4_7b-CGoKf_w6MMRMK9K5PzXjn4GdmSK' } }, // Replace with your IAM API key
url: 'https://8715b253-759d-4f15-b10e-c0d9e133d048-bluemix.cloudantnosqldb.appdomain.cloud', // Replace with your Cloudant URL
});
const db = cloudant.use('dealerships');
console.info('Connect success! Connected to DB');
return db;
} catch (err) {
console.error('Connect failure: ' + err.message + ' for Cloudant DB');
throw err;
}
}
let db;
(async () => {
db = await dbCloudantConnect();
})();
app.use(express.json());
// Define a route to get all dealerships with optional state and ID filters
app.get('/dealerships/get', (req, res) => {
const { state, id } = req.query;
// Create a selector object based on query parameters
const selector = {};
if (state) {
selector.state = state;
}
if (id) {
selector._id = id;
}
const queryOptions = {
selector,
limit: 10, // Limit the number of documents returned to 10
};
db.find(queryOptions, (err, body) => {
if (err) {
console.error('Error fetching dealerships:', err);
res.status(500).json({ error: 'An error occurred while fetching dealerships.' });
} else {
const dealerships = body.docs;
res.json(dealerships);
}
});
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
72 changes: 72 additions & 0 deletions functions/reviews.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
from cloudant.client import Cloudant
from cloudant.query import Query
from flask import Flask, jsonify, request
import atexit

#Add your Cloudant service credentials here
cloudant_username = '8715b253-759d-4f15-b10e-c0d9e133d048-bluemix'
cloudant_api_key = 'r6c5foCGS8FS4_7b-CGoKf_w6MMRMK9K5PzXjn4GdmSK'
cloudant_url = 'https://8715b253-759d-4f15-b10e-c0d9e133d048-bluemix.cloudantnosqldb.appdomain.cloud'
client = Cloudant.iam(cloudant_username, cloudant_api_key, connect=True, url=cloudant_url)

session = client.session()
print('Databases:', client.all_dbs())

db = client['reviews']

app = Flask(__name__)

@app.route('/api/get_reviews', methods=['GET'])
def get_reviews():
dealership_id = request.args.get('id')

# Check if "id" parameter is missing
if dealership_id is None:
return jsonify({"error": "Missing 'id' parameter in the URL"}), 400

# Convert the "id" parameter to an integer (assuming "id" should be an integer)
try:
dealership_id = int(dealership_id)
except ValueError:
return jsonify({"error": "'id' parameter must be an integer"}), 400

# Define the query based on the 'dealership' ID
selector = {
'dealership': dealership_id
}

# Execute the query using the query method
result = db.get_query_result(selector)

# Create a list to store the documents
data_list = []

# Iterate through the results and add documents to the list
for doc in result:
data_list.append(doc)

# Return the data as JSON
return jsonify(data_list)


@app.route('/api/post_review', methods=['POST'])
def post_review():
if not request.json:
abort(400, description='Invalid JSON data')

# Extract review data from the request JSON
review_data = request.json

# Validate that the required fields are present in the review data
required_fields = ['id', 'name', 'dealership', 'review', 'purchase', 'purchase_date', 'car_make', 'car_model', 'car_year']
for field in required_fields:
if field not in review_data:
abort(400, description=f'Missing required field: {field}')

# Save the review data as a new document in the Cloudant database
db.create_document(review_data)

return jsonify({"message": "Review posted successfully"}), 201

if __name__ == '__main__':
app.run(debug=True)
Binary file added server/db.sqlite3
Binary file not shown.
17 changes: 13 additions & 4 deletions server/djangoapp/admin.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
from django.contrib import admin
# from .models import related models


from .models import CarMake,CarModel
# Register your models here.

# CarModelInline class
class CarModelInline(admin.StackedInline):
model = CarModel
extra = 5

# CarModelAdmin class

class CarModelAdmin(admin.ModelAdmin):
list_display = ('name', "id", "type", "year", )
list_filter = ['id']
search_fields = ['name']
# CarMakeAdmin class with CarModelInline

class CarMakeAdmin(admin.ModelAdmin):
inlines=[CarModelInline]
list_display=("name", "description")
# Register models here
admin.site.register(CarModel,CarModelAdmin)
admin.site.register(CarMake,CarMakeAdmin)
57 changes: 55 additions & 2 deletions server/djangoapp/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,20 @@


# Create your models here.

CHOICES = [
("SUv", "SUV"),
("Wagon", "Wagon"),
]
# <HINT> Create a Car Make model `class CarMake(models.Model)`:
# - Name
# - Description
# - Any other fields you would like to include in car make model
# - __str__ method to print a car make object
class CarMake(models.Model):
name = models.CharField(null=False, max_length=30, default='new car make')
description = models.CharField(null=False, max_length=500)
def __str__(self):
return "Car Make:" + self.name


# <HINT> Create a Car Model model `class CarModel(models.Model):`:
Expand All @@ -19,9 +27,54 @@
# - Year (DateField)
# - Any other fields you would like to include in car model
# - __str__ method to print a car make object

class CarModel(models.Model):
make = models.ForeignKey(CarMake, on_delete=models.CASCADE)
name = models.CharField(null=False, max_length=30, default='new car model')
id = models.IntegerField(default=1,primary_key=True)
type = models.CharField(null=False, max_length=100, choices=CHOICES)
year = models.DateField(default=now)
description = models.CharField(null=False, max_length=500)
def __str__(self):
return "Name:" + self.name + "Description:" + self.description

# <HINT> Create a plain Python class `CarDealer` to hold dealer data

class CarDealer:
def __init__(self, address, city, full_name, id, lat, long, short_name, st, zip):
# Dealer address
self.address = address
# Dealer city
self.city = city
# Dealer Full Name
self.full_name = full_name
# Dealer id
self.id = id
# Location lat
self.lat = lat
# Location long
self.long = long
# Dealer short name
self.short_name = short_name
# Dealer state
self.st = st
# Dealer zip
self.zip = zip
def __str__(self):
return "Dealer name: " + self.full_name

# <HINT> Create a plain Python class `DealerReview` to hold review data
class DealerReview:
def __init__(self, dealership, name, purchase, review, purchase_date, car_make, car_model, car_year, id):
self.dealership = dealership
self.name = name
self.purchase = purchase
self.review = review
self.purchase_date = ""
self.car_make = ""
self.car_model = ""
self.car_year = ""
self.sentiment = ""
self.id = ""
def __str__(self):
return "Dealer name: " + self.name

124 changes: 119 additions & 5 deletions server/djangoapp/restapis.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,148 @@
import requests
import json
# import related models here
from .models import CarDealer, DealerReview
from requests.auth import HTTPBasicAuth

from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_watson.natural_language_understanding_v1 import Features,SentimentOptions
import time

# Create a `get_request` to make HTTP GET requests
# e.g., response = requests.get(url, params=params, headers={'Content-Type': 'application/json'},
# auth=HTTPBasicAuth('apikey', api_key))
def get_request(url, **kwargs):

# If argument contain API KEY
api_key = kwargs.get("api_key")
print("GET from {} ".format(url))
try:
if api_key:
params = dict()
params["text"] = kwargs["text"]
params["version"] = kwargs["version"]
params["features"] = kwargs["features"]
params["return_analyzed_text"] = kwargs["return_analyzed_text"]
response = requests.get(url, params=params, headers={'Content-Type': 'application/json'},
auth=HTTPBasicAuth('apikey', api_key))
else:
# Call get method of requests library with URL and parameters
response = requests.get(url, headers={'Content-Type': 'application/json'},
params=kwargs)
except:
# If any error occurs
print("Network exception occurred")

status_code = response.status_code
print("With status {} ".format(status_code))
json_data = json.loads(response.text)
return json_data

# Create a `post_request` to make HTTP POST requests
# e.g., response = requests.post(url, params=kwargs, json=payload)

def post_request(url, payload, **kwargs):
print(kwargs)
print("POST to {} ".format(url))
print(payload)
response = requests.post(url, params=kwargs, json=payload)
status_code = response.status_code
print("With status {} ".format(status_code))
json_data = json.loads(response.text)
return json_data

# Create a get_dealers_from_cf method to get dealers from a cloud function
# def get_dealers_from_cf(url, **kwargs):
# - Call get_request() with specified arguments
# - Parse JSON results into a CarDealer object list
def get_dealers_from_cf(url, **kwargs):
results = []
# Call get_request with a URL parameter
json_result = get_request(url)
if json_result:
# Get the row list in JSON as dealers
dealers = json_result
# For each dealer object
for dealer in dealers:
# Get its content in `doc` object
dealer_doc = dealer
# Create a CarDealer object with values in `doc` object
dealer_obj = CarDealer(address=dealer_doc["address"], city=dealer_doc["city"], full_name=dealer_doc["full_name"],
id=dealer_doc["id"], lat=dealer_doc["lat"], long=dealer_doc["long"],
short_name=dealer_doc["short_name"],
st=dealer_doc["st"], zip=dealer_doc["zip"])
results.append(dealer_obj)
return results

def get_dealer_by_id_from_cf(url, id, **kwargs):
results = []
json_result = get_request(url, id=id)
if json_result:
for dealer in json_result:
if (dealer["id"] == dealerId):
dealer_obj = CarDealer(address=dealer_doc["address"], city=dealer_doc["city"], full_name=dealer_doc["full_name"],
id=dealer_doc["id"], lat=dealer_doc["lat"], long=dealer_doc["long"],
short_name=dealer_doc["short_name"],
st=dealer_doc["st"], zip=dealer_doc["zip"])
results.append(dealer_obj)
return results

# Create a get_dealer_reviews_from_cf method to get reviews by dealer id from a cloud function
# def get_dealer_by_id_from_cf(url, dealerId):
# - Call get_request() with specified arguments
# - Parse JSON results into a DealerView object list
def get_dealer_reviews_from_cf(url, **kwargs):
results = []
id = kwargs.get("id")
if id:
json_result = get_request(url, id=id)
else:
json_result = get_request(url)
# print(json_result)
if json_result:
print("line 105",json_result)
reviews = json_result
for dealer_review in reviews:
review_obj = DealerReview(dealership=dealer_review["dealership"],
name=dealer_review["name"],
purchase=dealer_review["purchase"],
review=dealer_review["review"],
purchase_date=dealer_review["purchase_date"],
car_year=dealer_review["car_year"],
car_make=dealer_review["car_make"],
car_model=dealer_review["car_model"],
id=dealer_review["id"]
)
if "id" in dealer_review:
review_obj.id = dealer_review["id"]
if "purchase_date" in dealer_review:
review_obj.purchase_date = dealer_review["purchase_date"]
if "car_make" in dealer_review:
review_obj.car_make = dealer_review["car_make"]
if "car_model" in dealer_review:
review_obj.car_model = dealer_review["car_model"]
if "car_year" in dealer_review:
review_obj.car_year = dealer_review["car_year"]

sentiment = analyze_review_sentiments(review_obj.review)
print(sentiment)
review_obj.sentiment = sentiment
results.append(review_obj)


return results
# Create an `analyze_review_sentiments` method to call Watson NLU and analyze text
# def analyze_review_sentiments(text):
# - Call get_request() with specified arguments
# - Get the returned sentiment label such as Positive or Negative

def analyze_review_sentiments(text):
url = "https://api.us-east.natural-language-understanding.watson.cloud.ibm.com/instances/82a35a10-4051-4212-abd4-a1cd904ec957"
api_key = "5ZftXhylD7h-NR5ACWviXM1TRl2WOmhzoe9nXDXBZioq"
authenticator = IAMAuthenticator(api_key)
natural_language_understanding = NaturalLanguageUnderstandingV1(version='2021-08-01',authenticator=authenticator)
natural_language_understanding.set_service_url(url)
response = natural_language_understanding.analyze( text=text+"hello hello hello",features=Features(sentiment=SentimentOptions(targets=[text+"hello hello hello"]))).get_result()
label=json.dumps(response, indent=2)
label = response['sentiment']['document']['label']


return(label)


Loading