Spaces:
Sleeping
Sleeping
File size: 7,260 Bytes
c0ae570 616bff2 c0ae570 616bff2 99bad59 616bff2 99bad59 616bff2 c0ae570 616bff2 c0ae570 616bff2 8ef2fb2 beaa9aa 616bff2 d41d76f 616bff2 c0ae570 616bff2 beaa9aa 616bff2 615e960 616bff2 beaa9aa 616bff2 99bad59 616bff2 99bad59 616bff2 99bad59 616bff2 78e32b2 616bff2 99bad59 616bff2 78e32b2 99bad59 616bff2 c0ae570 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 |
from flask import Flask,render_template,request,Response,jsonify,redirect,url_for
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
import matplotlib.pyplot as plt
import pandas as pd
import os
import json
import re
from PIL import Image
import threading
import algorithms as alg
from io import BytesIO
app=Flask(__name__)
folder='static/images'
app.config["UPLOAD_FOLDER"]=folder
user="null"
pair={}
def pred_ver_and_save_data(img,img_name,data,digit,name,vector,brand,desc,cat,price):
try:
ans=alg.tell_vernelable(img)
except Exception as e:
ans=0.000001
vector=list(vector)
if ans>0.5:
data[f"id{digit+1}"]={"name":name,"description":desc,"reviews":[],"clicks":0,"category":cat,"price":price,"brand":brand,"img":f"images/{img_name}","vector":vector}
else:
data[f"id{digit+1}"]={"name":name,"description":desc,"reviews":[],"clicks":0,"category":cat,"price":price,"brand":brand,"img":'images/error.png',"vector":vector}
with open("products.json","w") as file:
json.dump(data,file)
file.close()
return 0
@app.route("/")
def page():
return render_template("index.html")
@app.route("/niche")
def niche():
return render_template("Niche.html")
@app.route("/product_panel/<product_id>",methods=["GET"])
def product_panel(product_id):
with open("products.json") as f:
data=json.load(f)
f.close()
vectors=[]
for ids in data:
vectors.append(data[ids]["vector"])
vect_arr=np.array(vectors)
to_compare=np.array(data[product_id]["vector"]).reshape(1,-1)
sim=[]
indexes=[]
rec={}
for vec in vect_arr:
sim.append(cosine_similarity(to_compare,vec.reshape(1,-1)))
sorted_sim=sorted(sim)[1:4]
for similar in sorted_sim:
indexes.append(sim.index(similar))
for i in indexes:
rec[list(data)[i]]=data[list(data)[i]]
return render_template("product_panel.html",product=data[product_id],rec_pro=rec)
@app.route("/products",methods=["GET"])
def products():
global user
with open("products.json") as f:
data=json.load(f)
f.close()
return render_template("products.html",products=data)
@app.route("/login",methods=['GET',"POST"])
def login():
global user
if request.method=="POST":
with open("seller.json") as f:
data=json.load(f)
name=request.form['name']
password=request.form['password']
if name not in list(data):
return redirect(url_for("sign_up"))
elif password=="":
return render_template("login.html")
elif password == str(data[name]['password']):
user=name
with open("products.json") as f:
pro=json.load(f)
f.close()
return redirect(url_for("products"))
else:
return render_template("login.html")
else:
return render_template("login.html")
@app.route("/sign_up",methods=["GET","POST"])
def sign_up():
global user
if request.method=="GET":
return render_template("Signup.html")
else:
with open("seller.json") as f:
data=json.load(f)
f.close()
name=request.form['name']
if name in list(data):
return redirect(url_for("login"))
else:
user=name
password=request.form['confirm']
data[name]={"password":password,"products":[],"reviews":[]}
with open("seller.json","w") as f:
json.dump(data,f)
f.close()
return redirect(url_for("niche"))
@app.route("/graph")
def graph():
with open("seller.json") as file:
data=json.load(file)
file.close()
a=[]
reviews=data['username1']['reviews']
for review in reviews:
sentiment=alg.give_sentiment(review)
a.append(sentiment)
df=pd.Series(a)
df=df.replace({1:"positive",0:"negative"})
data=df.value_counts()
fig,ax=plt.subplots()
data.plot(kind="bar" ,ax=ax)
plt.xlabel("review sentiment")
plt.ylabel("no of reviews")
plt.xticks(rotation=0)
img=BytesIO()
fig.savefig(img,format="png")
img.seek(0)
return Response(img, mimetype='image/png')
@app.route("/seller",methods=["GET","POST"])
def seller():
with open("seller.json") as file:
seller=json.load(file)
file.close()
reviews=seller[user]['reviews']
products=seller[user]['products']
with open("products.json") as file:
prod=json.load(file)
file.close()
return render_template("seller_dashboard.html",user=user,product=prod,ids=products,reviews=reviews)
@app.route("/tell",methods=['POST',"GET"])
def tell():
if request.method=="GET":
return render_template("add_product.html")
else:
img_file=request.files["image"]
img_name=img_file.filename
img_file=Image.open(img_file.stream).convert("RGB")
image_path=os.path.join(app.config['UPLOAD_FOLDER'],f"{img_name.split('.')[0]}.jpg")
img_file.save(image_path,"JPEG")
img=np.expand_dims(np.array(img_file.resize((256,256))).astype(np.float32)/255,axis=0)
with open("products.json") as file:
data=json.load(file)
file.close()
last=list(data.keys())[-1]
digit=int("".join(re.findall(r"\d",last)))
name=request.form["name"]
cat=request.form["category"]
desc=request.form["description"]
brand=request.form["brand"]
price=request.form['price']
vector=name+" "+brand+" "+desc
with open("tokenize_description.json","r") as file:
tokenizer=json.load(file)
with open("seller.json") as file:
seller=json.load(file)
new_product_id = f"id{digit+1}"
seller[user]["products"].append(new_product_id)
with open("seller.json","w") as file:
json.dump(seller,file)
file.close()
seq=[tokenizer[word] for word in vector.split() if word in tokenizer.keys()]
if len(seq)<=22:
vector=np.pad(seq,(22-len(seq),0))
else:
vector=np.array(vector[:22])
vector=[int(val) for val in vector]
threading.Thread(target=pred_ver_and_save_data,args=(img,img_name,data,digit,name,vector,brand,desc,cat,price)).start()
return render_template("seller_dashboard.html",user=user,ids=seller[user]["products"][:-1],product=data,reviews=seller[user]["reviews"])
@app.route("/chatbot",methods=["GET","POST"])
def chatbot():
if request.method=="GET":
return render_template("chatwindow.html",chat=pair)
else:
question=request.form['question']
question=question.lower()
ans=alg.ChatWithMe(question)
pair[question]=ans
return render_template("chatwindow.html",chat=pair)
@app.route("/predict", methods=["POST","GET"])
def predict():
if request.method=="POST":
data = request.json
input_text = data.get("text", "")
sugg=alg.pred_next(input_text,1)
return jsonify({"suggestions": [sugg]})
else:
return render_template("products.html")
if __name__=="__main__":
app.run(debug=True) |