File size: 7,248 Bytes
405af5a
 
 
17f8c84
247e064
cbd2dc3
1cb4f86
209d0f4
63666cb
71e0f1f
1cb4f86
 
63666cb
b27b67f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2827dd
1cb4f86
405af5a
b27b67f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
405af5a
b27b67f
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
201
202
203
204
205
206
207
208
209
210
211
212
import gradio as gr
from bs4 import BeautifulSoup
import requests
from youtube1 import getviews
from textsentiment import getresult
import math
#from python_actr import *
#from cogscidighum import *


#class myCelSci(Model):
#    pass
    
#def main(link):
#    response=getviews(link)+getresult("hello world")[0]["label"] + str(math.trunc(getresult("hello world")[0]["score"])*100/100)
#    return  response #result #soup.prettify()



import sqlite3
import huggingface_hub
import pandas as pd
import shutil
import os
import datetime
from apscheduler.schedulers.background import BackgroundScheduler

import random
import time

DB_FILE = "./reviews.db"

TOKEN = os.environ.get('HF_KEY')

repo = huggingface_hub.Repository(
    local_dir="data",
    repo_type="dataset",
    clone_from="CognitiveScience/csdhdata",
    use_auth_token=TOKEN
)
repo.git_pull()

# Set db to latest
shutil.copyfile("./data/reviews.db", DB_FILE)

# Create table if it doesn't already exist

db = sqlite3.connect(DB_FILE)
try:
    db.execute("SELECT * FROM reviews").fetchall()
    db.close()
except sqlite3.OperationalError:
    db.execute(
        '''
        CREATE TABLE reviews (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                              created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
                              name TEXT, review INTEGER, comments TEXT)
        ''')
    db.commit()
    db.close()


def get_latest_reviews(db: sqlite3.Connection):
    reviews = db.execute("SELECT * FROM reviews ORDER BY id DESC limit 10").fetchall()
    total_reviews = db.execute("Select COUNT(id) from reviews").fetchone()[0]
    reviews = pd.DataFrame(reviews, columns=["id", "date_created", "name", "review", "comments"])
    return reviews, total_reviews


def add_review(name: str, review: int, comments: str):
    db = sqlite3.connect(DB_FILE)
    cursor = db.cursor()
    cursor.execute("INSERT INTO reviews(name, review, comments) VALUES(?,?,?)", [name, review, comments])
    db.commit()
    reviews, total_reviews = get_latest_reviews(db)
    db.close()
    return reviews, total_reviews

def load_data():
    db = sqlite3.connect(DB_FILE)
    reviews, total_reviews = get_latest_reviews(db)
    db.close()
    return reviews, total_reviews
    
def delete_review(id: int):
    db = sqlite3.connect(DB_FILE)
    cursor = db.cursor()
    cursor.execute("DELETE FROM reviews WHERE id = ?", [id])
    db.commit()
    reviews, total_reviews = get_latest_reviews(db)
    db.close()
    return reviews, total_reviews
    
def delete_all_reviews():
    db = sqlite3.connect(DB_FILE)
    cursor = db.cursor()
    cursor.execute("DELETE FROM reviews")
    db.commit()
    reviews, total_reviews = get_latest_reviews(db)
    db.close()
    return reviews, total_reviews
def celsci(link):
    response=getviews(link)+getresult("hello world")[0]["label"] + str(math.trunc(getresult("hello world")[0]["score"])*100/100)
    return  response #result #soup.prettify()

with gr.Blocks() as demo:
    with gr.Row():
        with gr.Column():   
                chatbot3 = gr.Chatbot()
                msg3 = gr.Textbox()
                clear3 = gr.ClearButton([msg2, chatbot2])
            
                def respond3(message, chat_history):
                    bot_message = random.choice(["How are you3?", "I love you3", "I'm very hungry3"])
                    chat_history.append((message, bot_message))
                    time.sleep(2)
                    
                    return "", chat_history
            
                msg2.submit(respond3, [msg3, chatbot3], [msg3, chatbot3])
            
    with gr.Row():
        with gr.Column():            
                name = gr.Textbox(label="Name", placeholder="What is your name?")
                review = gr.Radio(label="How satisfied are you with using gradio?", choices=[1, 2, 3, 4, 5])
                comments = gr.Textbox(label="Comments", lines=10, placeholder="Do you have any feedback on gradio?")
                submit = gr.Button(value="Submit Feedback")
        with gr.Column():
                chatbot = gr.Chatbot()
                msg = gr.Textbox()
                clear = gr.ClearButton([msg, chatbot])
            
                def respond(message, chat_history):
                    bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"])
                    chat_history.append((message, bot_message))
                    time.sleep(2)
                    
                    return "", chat_history
            
                msg.submit(respond, [msg, chatbot], [msg, chatbot])
        
        with gr.Column():
                chatbot2 = gr.Chatbot()
                msg2 = gr.Textbox()
                clear2 = gr.ClearButton([msg2, chatbot2])
            
                def respond2(message, chat_history):
                    bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"])
                    chat_history.append((message, bot_message))
                    time.sleep(2)
                    
                    return "", chat_history
            
                msg2.submit(respond2, [msg2, chatbot2], [msg2, chatbot2])

        with gr.Column():
                submitsave = gr.Button(value="Save")
            
                def backup_db2():
                    shutil.copyfile(DB_FILE, "./data/reviews.db")
                    db = sqlite3.connect(DB_FILE)
                    reviews = db.execute("SELECT * FROM reviews").fetchall()
                    pd.DataFrame(reviews).to_csv("./data/reviews.csv", index=False)
                    print("updating db")
                    repo.push_to_hub(blocking=False, commit_message=f"Updating data at {datetime.datetime.now()}")
                submit.click(backup_db2)
        with gr.Column():
            with gr.Box():
                gr.Code(
                value="""def hello_world():
            return "Hello, world!"
            
        print(hello_world())""",
                language="python",
                interactive=True,
                show_label=False,
            )
                gr.Markdown("Based on dataset [here](https://huggingface.co/datasets/freddyaboulton/gradio-reviews)")
                data = gr.Dataframe()
            count = gr.Number(label="Total number of reviews")
            
    submit.click(add_review, [name, review, comments], [data, count])

    record2del = gr.Textbox(label="Id: ", lines=1, placeholder="to delete?")

    submit2 = gr.Button(value="Delete Review")
    id_input = gr.Number(value=202, visible=False)
    submit2.click(delete_review, id_input)



    submit3 = gr.Button(value="Delete All Reviews")
    submit3.click(delete_all_reviews)


    demo.load(load_data, None, [data, count])

def backup_db():
    shutil.copyfile(DB_FILE, "./data/reviews.db")
    db = sqlite3.connect(DB_FILE)
    reviews = db.execute("SELECT * FROM reviews").fetchall()
    pd.DataFrame(reviews).to_csv("./data/reviews.csv", index=False)
    print("updating db")
    repo.push_to_hub(blocking=False, commit_message=f"Updating data at {datetime.datetime.now()}")


scheduler = BackgroundScheduler()
scheduler.add_job(func=backup_db, trigger="interval", seconds=60)
scheduler.start()


demo.launch()