Commit 7e519a9f authored by  Joel  Oksanen's avatar Joel Oksanen
Browse files

Implemented DataLoader class. Added star rating to app

parent 5e2a77a7
import pandas as pd
class DataLoader:
data_location = 'amazon_reviews_us_Camera_v1_00.tsv'
reviews = pd.read_csv(data_location, sep='\t', error_bad_lines=False)
def get_reviews(self, product_id):
return self.reviews[self.reviews['product_id'] == product_id].reset_index(drop=True)
def get_product_name(self, product_id):
return self.get_reviews(product_id)['product_title'][0]
def get_avg_star_rating(self, product_id):
return self.get_reviews(product_id)['star_rating'].mean()
......@@ -23,6 +23,5 @@ battery: ['battery'],
flash: ['flash'],
audio: ['audio', 'sound'],
price: ['price', 'value', 'cost'],
shipping: ['ship'],
shipping: ['ship']
}
......@@ -4,4 +4,6 @@ from . import views
urlpatterns = [
path('', views.index, name='index'),
path('product/', views.product, name='product'),
path('message/', views.message, name='message')
]
from django.http import JsonResponse
from django.http import JsonResponse, HttpResponse
import json
from django.views.decorators.csrf import csrf_exempt
import sys
sys.path.append('/Users/joeloksanen/individual_project/ADA')
from DataLoader import DataLoader
dl = DataLoader()
def index(request):
return HttpResponse("OK")
def product(request):
id = request.GET.get('id', '')
name = 'Joel'
price = 1.2
name = dl.get_product_name(id)
star_rating = dl.get_avg_star_rating(id)
imageURL = 'https://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&MarketPlace=US&ASIN=' + id + '&ServiceVersion=20070822&ID=AsinImage&WS=1&Format=SL250'
return JsonResponse({'id': id, 'name': name, 'price': price, 'imageURL': imageURL})
return JsonResponse({'id': id, 'name': name, 'starRating': star_rating, 'imageURL': imageURL})
@csrf_exempt
def message(request):
parsed = json.loads(request.body)
arg_id = parsed['argumentID']
query_id = parsed['queryID']
print(arg_id)
print(query_id)
return HttpResponse("OK")
......@@ -29,6 +29,7 @@
9449FE4D2404561400025F70 /* ArgumentQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9449FE4C2404561400025F70 /* ArgumentQuery.swift */; };
9449FE4F240533FD00025F70 /* QueryOptionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9449FE4E240533FD00025F70 /* QueryOptionView.swift */; };
9449FE5124053DA500025F70 /* ChatManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9449FE5024053DA500025F70 /* ChatManager.swift */; };
94BE1EEB2407E26900741749 /* RatingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94BE1EEA2407E26900741749 /* RatingView.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
......@@ -56,6 +57,7 @@
9449FE4C2404561400025F70 /* ArgumentQuery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArgumentQuery.swift; sourceTree = "<group>"; };
9449FE4E240533FD00025F70 /* QueryOptionView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QueryOptionView.swift; sourceTree = "<group>"; };
9449FE5024053DA500025F70 /* ChatManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatManager.swift; sourceTree = "<group>"; };
94BE1EEA2407E26900741749 /* RatingView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RatingView.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
......@@ -136,6 +138,7 @@
9449FE2E2402C8C500025F70 /* ProductView.swift */,
9449FE322402CBD400025F70 /* ProductInfo.swift */,
9449FE362402D29E00025F70 /* Product.swift */,
94BE1EEA2407E26900741749 /* RatingView.swift */,
);
path = Product;
sourceTree = "<group>";
......@@ -229,6 +232,7 @@
9449FE352402CCDA00025F70 /* ConnectionManager.swift in Sources */,
9449FE1D2402C84F00025F70 /* SceneDelegate.swift in Sources */,
9449FE1F2402C84F00025F70 /* ContentView.swift in Sources */,
94BE1EEB2407E26900741749 /* RatingView.swift in Sources */,
9449FE332402CBD400025F70 /* ProductInfo.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
......
{
"images" : [
{
"idiom" : "universal",
"filename" : "star_border.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
\ No newline at end of file
{
"images" : [
{
"idiom" : "universal",
"filename" : "star_fill.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
\ No newline at end of file
......@@ -19,6 +19,7 @@ class ChatManager: ObservableObject {
}
func sendQuery(query: ArgumentQuery) {
connectionManager.sendQuery(query)
sent = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
self.sent = false
......
......@@ -17,8 +17,8 @@ class ConnectionManager: ObservableObject {
requestProduct(id: "B00RTGK0N0")
}
func requestProduct(id: String) {
let url = URL(string: "http://192.168.0.13:8000/ios_server/?id=" + id)!
private func requestProduct(id: String) {
let url = URL(string: "http://192.168.0.13:8000/ios_server/product/?id=" + id)!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
......@@ -27,7 +27,8 @@ class ConnectionManager: ObservableObject {
DispatchQueue.main.async {
self.requestImage(at: productInfo.imageURL)
self.product.name = productInfo.name
self.product.price = productInfo.price
self.product.starRating = productInfo.starRating
print(productInfo.starRating)
}
} catch let parseError {
print(parseError)
......@@ -39,7 +40,7 @@ class ConnectionManager: ObservableObject {
task.resume()
}
func requestImage(at urlString: String) {
private func requestImage(at urlString: String) {
let url = URL(string: urlString)!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
......@@ -53,8 +54,46 @@ class ConnectionManager: ObservableObject {
task.resume()
}
func sendQuery(_ query: ArgumentQuery) {
let url = URL(string: "http://192.168.0.13:8000/ios_server/message/")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
guard let data = try? JSONEncoder().encode(query) else {
return
}
let task = URLSession.shared.uploadTask(with: request, from: data) { receivedData, response, error in
if let error = error {
self.handleClientError(error: error)
return
}
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
self.handleServerError(response: response!)
return
}
if let mimeType = httpResponse.mimeType,
mimeType == "text/html",
let receivedData = receivedData {
DispatchQueue.main.async {
print(receivedData)
}
}
}
task.resume()
}
func addMessage(message: Message) {
messages.append(message)
}
private func handleClientError(error: Error) {
print("Client error occurred")
}
private func handleServerError(response: URLResponse) {
print("Server error occurred")
}
}
......@@ -10,14 +10,14 @@ import UIKit
struct Product {
var name: String
var starRating: Double
var image: UIImage
init() {
self.name = ""
self.price = 0
self.starRating = 0
self.image = UIImage()
}
var name: String
var price: Double
var image: UIImage
}
......@@ -8,16 +8,16 @@
struct ProductInfo: Decodable {
let id: String
let name: String
let starRating: Double
let imageURL: String
init() {
self.id = ""
self.name = ""
self.price = 0
self.starRating = 0
self.imageURL = ""
}
let id: String
let name: String
let price: Double
let imageURL: String
}
......@@ -22,9 +22,12 @@ struct ProductView: View {
VStack {
Spacer()
HStack(alignment: .top) {
Text(connectionManager.product.name)
.font(Font.custom("Helvetica Neue", size: 14))
.foregroundColor(Color.gray)
VStack {
Text(connectionManager.product.name)
.font(Font.custom("Helvetica Neue", size: 14))
.foregroundColor(Color.gray)
RatingView(starRating: $connectionManager.product.starRating)
}
Spacer()
Image(uiImage: connectionManager.product.image)
.resizable()
......
//
// StarView.swift
// ADAbot
//
// Created by Joel Oksanen on 27.2.2020.
// Copyright © 2020 Joel Oksanen. All rights reserved.
//
import SwiftUI
struct RatingView: View {
let dim: CGFloat = 16
@Binding var starRating: Double
var fullStars: Int {
get {
return Int(starRating.rounded(.down))
}
}
var starFrac: CGFloat {
get {
let frac = CGFloat(starRating - starRating.rounded(.down))
return frac >= 0.25 ? (frac <= 0.75 ? frac : 0.75) : 0.25
}
}
var emptyStars: Int {
get {
let n = 4 - fullStars
return n > 0 ? n : 0
}
}
var body: some View {
HStack(spacing: 3) {
ForEach(0..<fullStars, id: \.self) { i in
ZStack {
Image("star_fill")
.renderingMode(.template)
.resizable()
.aspectRatio(contentMode: .fill)
.foregroundColor(Color(red: 254/255, green: 200/255, blue: 0/255))
Image("star_border")
.renderingMode(.template)
.resizable()
.aspectRatio(contentMode: .fill)
.foregroundColor(Color(red: 176/255, green: 131/255, blue: 58/255))
}
.frame(width: self.dim, height: self.dim)
}
if starFrac != 0 {
ZStack(alignment: .leading) {
Image("star_fill")
.renderingMode(.template)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: self.dim * starFrac, height: self.dim, alignment: .leading)
.foregroundColor(Color(red: 254/255, green: 200/255, blue: 0/255))
.clipped()
Image("star_border")
.renderingMode(.template)
.resizable()
.aspectRatio(contentMode: .fill)
.foregroundColor(Color(red: 176/255, green: 131/255, blue: 58/255))
.frame(width: self.dim, height: self.dim)
}
}
ForEach(0..<emptyStars, id: \.self) { i in
Image("star_border")
.renderingMode(.template)
.resizable()
.aspectRatio(contentMode: .fill)
.foregroundColor(Color(red: 176/255, green: 131/255, blue: 58/255))
.frame(width: self.dim, height: self.dim)
}
Spacer()
}
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment