1s commited on
Commit
ef41b1d
1 Parent(s): 82c2688

Create Orig file

Browse files
Files changed (1) hide show
  1. Orig file +87 -0
Orig file ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import logging
4
+ import requests
5
+ from urllib.parse import quote
6
+ import yaml
7
+
8
+ class Products:
9
+ data = [] # Список, в котором будут словари
10
+
11
+ def read_yaml_file(self, filename):
12
+ """Read the data from a YAML file and return a list of dictionaries"""
13
+ with open(filename, 'r') as file:
14
+ self.data = yaml.load(file, Loader=yaml.FullLoader)
15
+
16
+ def write_yaml_file(self, filename):
17
+ """Write the data in YAML format to a file"""
18
+ with open(filename, 'w') as file:
19
+ yaml.dump(self.data, file)
20
+
21
+ def sortProducts(self, criteria: str, order: bool = False):
22
+ """Sort list of products by given criteria:
23
+ \n price - price of a product
24
+ \n rating - total rating of a seller
25
+ \n sold - the amount of items sold
26
+ \n\n order - asc=0, desc=1
27
+ """
28
+ self.data.sort(key=operator.itemgetter(criteria), reverse=order)
29
+
30
+ def parseAPI(self, query):
31
+ """Find all elements on page and store them into the dictionary using plati.ru API"""
32
+ self.data = []
33
+ pagesize = 499
34
+ contents = requests.get(f"https://plati.io/api/search.ashx?query={quote(query)}&pagesize={pagesize}&visibleOnly=true&response=json").json()
35
+ total_pages = int(contents['Totalpages'])
36
+ for entry in contents['items']:
37
+ self.data.append(
38
+ {'name': entry['name'], 'link': entry['url'], 'price': int(entry['price_rur']), 'rating': float(entry['seller_rating']), 'sold': int(entry['numsold'])})
39
+ if total_pages > 1:
40
+ for i in range(2, total_pages + 1):
41
+ contents = requests.get(f"https://plati.io/api/search.ashx?query={quote(query)}&pagesize={pagesize}&pagenum={i}&visibleOnly=true&response=json").json()
42
+ for entry in contents['items']:
43
+ self.data.append(
44
+ {'name': entry['name'], 'link': entry['url'], 'price': int(entry['price_rur']), 'rating': float(entry['seller_rating']), 'sold': int(entry['numsold'])})
45
+
46
+ # Функция поиска, которая будет вызываться из интерфейса Gradio
47
+ def search(query):
48
+ logging.info(f"Search started with query: {query}")
49
+ products = Products()
50
+ products.parseAPI(query)
51
+ products.write_yaml_file("cache.yaml")
52
+ products.read_yaml_file("cache.yaml")
53
+ logging.info(f"Search results: {products.data}")
54
+
55
+ # Создаем новый DataFrame из списка словарей products.data
56
+ df = pd.DataFrame(products.data)
57
+ return df # Возвращаем DataFrame
58
+
59
+ # Добавляем функцию greet для демонстрации
60
+ def greet(name):
61
+ return "Hello " + name + "!!"
62
+
63
+ # Создание Gradio интерфейса
64
+ def create_interface():
65
+ with gr.Blocks() as demo:
66
+ gr.Markdown("# Plati.market Parser and Greet Function")
67
+ gr.Markdown("### Greeting Section")
68
+ greet_input = gr.Textbox(label="Enter your name")
69
+ greet_button = gr.Button("Greet")
70
+ greet_output = gr.Textbox(label="Greeting")
71
+ greet_button.click(fn=greet, inputs=greet_input, outputs=greet_output)
72
+
73
+ gr.Markdown("### Plati.market Search Section")
74
+ gr.Markdown("Input what you like to find in the field below. The results will be displayed in the table.")
75
+ search_input = gr.Textbox(label="Search Query")
76
+ search_button = gr.Button("Search")
77
+ data_table = gr.Dataframe(headers=["name", "link", "price", "rating", "sold"], interactive=True, label="Search Results")
78
+ search_button.click(fn=search, inputs=search_input, outputs=data_table)
79
+
80
+ return demo
81
+
82
+ if __name__ == "__main__":
83
+ # Настройка логирования
84
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
85
+
86
+ demo = create_interface()
87
+ demo.launch()