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

IBM project #173

Open
wants to merge 23 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
30 changes: 30 additions & 0 deletions server/deployment.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
run: dealership
name: dealership
spec:
replicas: 1
selector:
matchLabels:
run: dealership
strategy:
rollingUpdate:
maxSurge: 25%
maxUnavailable: 25%
type: RollingUpdate
template:
metadata:
labels:
run: dealership
spec:
containers:
- image: us.icr.io/your_namespace/dealership:latest
imagePullPolicy: Always
name: dealership
ports:
- containerPort: 8000
protocol: TCP
restartPolicy: Always

19 changes: 11 additions & 8 deletions server/djangoapp/admin.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
# djangoapp/admin.py
from django.contrib import admin
# from .models import related models
from .models import CarMake, CarModel

class CarModelInline(admin.TabularInline):
model = CarModel
extra = 1 # Number of empty forms to display for adding related CarModel objects

# Register your models here.
@admin.register(CarMake)
class CarMakeAdmin(admin.ModelAdmin):
inlines = [CarModelInline]

# CarModelInline class
@admin.register(CarModel)
class CarModelAdmin(admin.ModelAdmin):
list_display = ('car_make', 'name', 'car_type', 'year', 'dealer_id') # Customize the fields displayed in the admin list view

# CarModelAdmin class

# CarMakeAdmin class with CarModelInline

# Register models here
80 changes: 80 additions & 0 deletions server/djangoapp/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,19 @@
# - 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 of the car make
name = models.CharField(max_length=100)

# Description of the car make
description = models.TextField()

# Any other fields you'd like to include
# For example, founding year of the car make
founding_year = models.IntegerField()

def __str__(self):
return self.name


# <HINT> Create a Car Model model `class CarModel(models.Model):`:
Expand All @@ -19,9 +32,76 @@
# - 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):
# Many-to-One relationship to CarMake model
car_make = models.ForeignKey(CarMake, on_delete=models.CASCADE)

# Dealer ID referring to a dealer in Cloudant database
dealer_id = models.IntegerField()

# Name of the car model
name = models.CharField(max_length=100)

# Type of the car model with limited choices
CAR_TYPES = [
('SEDAN', 'Sedan'),
('SUV', 'SUV'),
('WAGON', 'Wagon'),
]
car_type = models.CharField(max_length=5, choices=CAR_TYPES)

# Year of the car model
year = models.DateField()

# Any other fields you'd like to include
# For example, engine type, fuel type, etc.
engine_type = models.CharField(max_length=50)

def __str__(self):
return f"{self.car_make} - {self.name} ({self.year.year})"


# <HINT> Create a plain Python class `CarDealer` to hold dealer data
class CarDealer(models.Model):
# Fields for CarDealer model
name = models.CharField(max_length=100)
location = models.CharField(max_length=255)
# Add any other fields you want for the CarDealer model
full_name = models.CharField(max_length=100)
id = models.IntegerField(primary_key=True) # Assuming id is the primary key
lat = models.FloatField()
long = models.FloatField()
short_name = models.CharField(max_length=50)
st = models.CharField(max_length=50)
zip = models.CharField(max_length=20)

def __str__(self):
return "Dealer name: " + self.full_name

# <HINT> Create a plain Python class `DealerReview` to hold review data
class DealerReview(models.Model):
# Many-to-One relationship to CarDealer model
car_dealer = models.ForeignKey(CarDealer, on_delete=models.CASCADE)

# Fields for DealerReview model
reviewer_name = models.CharField(max_length=100)
review_text = models.TextField()
rating = models.PositiveIntegerField()
dealership = models.CharField(max_length=100)
name = models.CharField(max_length=100)
purchase = models.CharField(max_length=100)
review = models.TextField()
purchase_date = models.DateField()
car_make = models.CharField(max_length=100)
car_model = models.CharField(max_length=100)
car_year = models.IntegerField()
sentiment = models.CharField(max_length=10) # Positive, Neutral, Negative
id = models.IntegerField(primary_key=True) # Assuming this is the unique identifier

def __str__(self):
return f"{self.dealership} - {self.name}"

def __str__(self):
return f"{self.car_dealer} - {self.reviewer_name}"


120 changes: 116 additions & 4 deletions server/djangoapp/restapis.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,145 @@
import json
# import related models here
from requests.auth import HTTPBasicAuth

from .models import CarDealer, DealerReview

# 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, api_key=None, **kwargs):
print(kwargs)
print("GET from {} ".format(url))
try:
# If an API key is provided, use authentication
if api_key:
response = requests.get(
url,
headers={'Content-Type': 'application/json'},
params=kwargs,
auth=HTTPBasicAuth('apikey', api_key)
)
else:
# If no API key is provided, make a regular GET request
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, json_payload, **kwargs):
print(kwargs)
print("POST to {} ".format(url))
try:
# Call post method of requests library with URL, JSON payload, and parameters
response = requests.post(url, json=json_payload, 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 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, **kwargs)
if json_result:
# Get the row list in JSON as dealers
dealers = json_result["rows"]
# For each dealer object
for dealer in dealers:
# Get its content in `doc` object
dealer_doc = dealer["doc"]
# 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

# 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
# restapis.py

def get_dealer_reviews_from_cf(url, dealer_id, api_key):
results = []
# Call get_request with a URL parameter
json_result = get_request(url, dealerId=dealer_id)
if json_result:
# Get the row list in JSON as reviews
reviews = json_result["reviews"]
# For each review object
for review in reviews:
# Create a DealerReview object with values in the review object
review_obj = DealerReview(
dealership=review["dealership"],
name=review["name"],
purchase=review["purchase"],
review=review["review"],
purchase_date=review["purchase_date"],
car_make=review["car_make"],
car_model=review["car_model"],
car_year=review["car_year"],
sentiment=None # Initialize sentiment as None
)

# Analyze sentiment and assign to the review object
review_obj.sentiment = analyze_review_sentiments(api_key, review_obj.review)

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(api_key, text):
# Watson NLU URL for analyzing sentiment
url = "your_watson_nlu_url/v1/analyze"

# Parameters for the Watson NLU request
params = {
"text": text,
"version": "2021-03-25", # Specify the version of Watson NLU
"features": "emotion,sentiment",
"return_analyzed_text": True
}

try:
# Call get_request with Watson NLU URL and parameters
response = get_request(url, api_key=api_key, **params)

# Check if the response contains sentiment information
if "sentiment" in response:
return response["sentiment"]
else:
return None
except Exception as e:
print(f"Error analyzing sentiment: {e}")
return None






20 changes: 20 additions & 0 deletions server/djangoapp/templates/djangoapp/About.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<!-- ./server/djangoapp/templates/djangoapp/about.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>About Us</title>
</head>
<body>
<h1>Welcome to Best Cars dealership, home to the best cars in North America. We sell domestic and imported cars at reasonable prices.</h1>
<!-- Add additional information here -->
<nav class="navbar navbar-light bg-light">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="{% url 'static_template' %}">Home</a>
<a class="navbar-brand" href="{% url 'about_us' %}">About Us</a>
</div>
</div>
</nav>
</body>
</html>
18 changes: 18 additions & 0 deletions server/djangoapp/templates/djangoapp/ContactUs.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Us - Best Cars Dealership</title>
</head>
<body>
<h1>Contact Us</h1>
<p>
Welcome to Best Cars Dealership. For inquiries, please contact us at the following address and telephone number:
</p>
<p>
Address: 123 Main Street, Cityville<br>
Telephone: +1 (123) 456-7890
</p>
<a href="{% url 'contact_us' %}">Contact Us</a>
</body>
</html>
Loading