NguyNhu commited on
Commit
97cb158
·
verified ·
1 Parent(s): be40855

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +103 -82
app.py CHANGED
@@ -3,97 +3,118 @@
3
  import gradio as gr
4
  import sys
5
  import os
 
6
 
7
  # Thêm đường dẫn thư mục hiện tại vào sys.path để Python có thể tìm thấy script scraper
8
  sys.path.append(os.path.dirname(os.path.abspath(__file__)))
9
 
10
- # Nhớ thay thế 'yellow_pages_scraper' bằng tên file .py thật của script scraper của bạn
11
- # đảm bảo hàm 'parse_listing(keyword, location)' tồn tại trong file đó.
12
  try:
13
- # Import hàm cạo dữ liệu từ script chính của bạn
14
- from yellow_pages_scraper import parse_listing
15
- # Đánh dấu là import thành công để biết hàm cạo có sẵn
16
- scraper_function_available = True
17
- except ModuleNotFoundError:
18
- scraper_function_available = False
19
- print("Lỗi: Không tìm thấy file 'yellow_pages_scraper.py' hoặc hàm 'parse_listing'.")
20
- print("Vui lòng đảm bảo script cạo dữ liệu của bạn tên là 'yellow_pages_scraper.py'")
21
- print("và chứa hàm 'parse_listing(keyword, location)' trong cùng thư mục.")
22
- # Định nghĩa một hàm giả để ứng dụng Gradio vẫn chạy nhưng báo lỗi rõ ràng
23
- def parse_listing(keyword, location):
24
- return [{"error": "Scraper script file or function not found."}]
25
- except ImportError as e:
26
- scraper_function_available = False
27
- print(f"Lỗi Import từ script scraper: {e}")
28
- def parse_listing(keyword, location):
29
- return [{"error": f"Error importing from scraper script: {e}"}]
30
-
31
-
32
- def run_scraper(keyword, location):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  """
34
- Hàm này nhận input từ Gradio, gọi script cạo dữ liệu định dạng output.
35
  """
36
- if not scraper_function_available:
37
- return "Lỗi: Script cạo dữ liệu chưa được tải đúng cách. Vui lòng kiểm tra file và tên hàm."
 
 
 
 
 
 
 
38
 
39
- if not keyword or not location:
40
- return "Vui lòng nhập cả Từ khóa tìm kiếm và Địa điểm."
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- print(f"Đang cạo dữ liệu cho: Từ khóa='{keyword}', Địa điểm='{location}'")
 
 
 
 
 
 
 
 
43
 
44
- try:
45
- # Gọi hàm cạo dữ liệu từ script của bạn
46
- # Giả định hàm parse_listing trả về một list các dictionary
47
- scraped_data = parse_listing(keyword, location)
48
-
49
- if not scraped_data or (len(scraped_data) == 1 and "error" in scraped_data[0]):
50
- # Xử lý trường hợp không có kết quả hoặc có lỗi từ hàm parse_listing
51
- if scraped_data and "error" in scraped_data[0]:
52
- return f"Script cạo dữ liệu báo lỗi: {scraped_data[0]['error']}"
53
- return "Không tìm thấy kết quả nào cho tìm kiếm này hoặc script cạo dữ liệu không hoạt động đúng."
54
-
55
-
56
- # Định dạng dữ liệu để hiển thị trong output text area của Gradio
57
- output_text = "Kết quả cạo dữ liệu:\n\n"
58
- for i, item in enumerate(scraped_data):
59
- output_text += f"--- Doanh nghiệp {i+1} ---\n"
60
- # Sử dụng .get() để tránh lỗi nếu một key không tồn tại trong dictionary
61
- # Điều chỉnh các key này ('business_name', 'telephone', v.v.)
62
- # để phù hợp với các key mà script scraper của bạn sử dụng trong dictionary kết quả
63
- output_text += f"Tên: {item.get('business_name', 'N/A')}\n"
64
- output_text += f"Điện thoại: {item.get('telephone', 'N/A')}\n"
65
- output_text += f"Địa chỉ: {item.get('street', 'N/A')}, {item.get('locality', 'N/A')}, {item.get('region', 'N/A')} {item.get('zipcode', 'N/A')}\n"
66
- output_text += f"Website: {item.get('website', 'N/A')}\n"
67
- output_text += f"Hạng mục: {item.get('category', 'N/A')}\n"
68
- output_text += f"Đánh giá: {item.get('rating', 'N/A')}\n"
69
- output_text += f"Rank: {item.get('rank', 'N/A')}\n"
70
- output_text += f"URL: {item.get('url', 'N/A')}\n" # Đảm bảo script scraper có cạo URL
71
- output_text += "-----------------------\n\n"
72
-
73
- return output_text
74
-
75
- except Exception as e:
76
- # Xử lý các lỗi không mong muốn khác
77
- print(f"Đã xảy ra lỗi không xác định khi chạy scraper: {e}")
78
- import traceback
79
- traceback.print_exc() # In traceback để debug
80
- return f"Đã xảy ra lỗi không xác định khi chạy scraper: {e}"
81
 
82
  # Tạo giao diện Gradio
83
- iface = gr.Interface(
84
- fn=run_scraper, # Hàm sẽ được gọi khi nhấn nút
85
- inputs=[
86
- gr.Textbox(label="Từ khóa tìm kiếm (ví dụ: restaurants)"),
87
- gr.Textbox(label="Địa điểm (ví dụ: Boston,MA)")
88
- ],
89
- outputs=gr.Textbox(label="Kết quả cạo dữ liệu", lines=20, max_lines=50), # Hiển thị kết quả trong Textbox lớn
90
- title="Yellow Pages Scraper Demo",
91
- description="Nhập từ khóa và địa điểm để chạy script cạo thông tin doanh nghiệp từ Yellow Pages.",
92
- allow_flagging="never", # Tắt tính năng flagging nếu không cần thiết
93
- analytics_enabled=False # Tắt analytics nếu không cần thiết
94
- )
95
-
96
- # Chạy ứng dụng Gradio
97
- # Trong Hugging Face Space, dòng này sẽ tự động được gọi
98
- # Khi chạy cục bộ, nó sẽ mở giao diện trong trình duyệt
99
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import gradio as gr
4
  import sys
5
  import os
6
+ import subprocess # Để chạy các script như subprocess nếu chúng không có hàm dễ gọi
7
 
8
  # Thêm đường dẫn thư mục hiện tại vào sys.path để Python có thể tìm thấy script scraper
9
  sys.path.append(os.path.dirname(os.path.abspath(__file__)))
10
 
11
+ # --- Cách 1: Import hàm trực tiếp (Nếu script hàm dễ gọi) ---
12
+ # dụ cho yellowpages.py nếu nó có hàm parse_listing(keyword, location)
13
  try:
14
+ from yellowpages import parse_listing_function # Giả sử hàm tên là parse_listing_function
15
+ yp_scraper_available = True
16
+ except ImportError:
17
+ yp_scraper_available = False
18
+ print("Cảnh báo: Không thể import hàm từ yellowpages.py. Chức năng này sẽ không hoạt động.")
19
+ # Hàm giả khi import lỗi
20
+ def parse_listing_function(keyword, location):
21
+ return [{"error": "yellowpages.py scraper function not available."}]
22
+
23
+
24
+ # --- Cách 2: Chạy script như một tiến trình con (Nếu script chỉ chạy từ command line) ---
25
+ # Cách này phức tạp hơn cần bắt output từ subprocess
26
+ def run_yellowpages_cli(keyword, location):
27
+ try:
28
+ # Thay thế 'python yellowpages.py' bằng lệnh chính xác để chạy script
29
+ # Cần xử lý output từ console để trả về cho Gradio
30
+ result = subprocess.run(
31
+ ["python", "yellowpages.py", keyword, location], # Đây là ví dụ, cần đúng cú pháp script
32
+ capture_output=True,
33
+ text=True,
34
+ check=True # Báo lỗi nếu script trả về mã lỗi khác 0
35
+ )
36
+ # Output thành công thường nằm trong stdout
37
+ # Cần phân tích cú pháp stdout nếu nó trả về dữ liệu cấu trúc (JSON, CSV in console)
38
+ # hoặc trả về nguyên văn nếu script in kết quả dễ đọc
39
+ return result.stdout
40
+ except subprocess.CalledProcessError as e:
41
+ return f"Lỗi khi chạy scraper từ command line: {e.stderr}"
42
+ except FileNotFoundError:
43
+ return "Lỗi: Không tìm thấy file yellowpages.py để chạy."
44
+
45
+
46
+ # Hàm chính được gọi từ Gradio
47
+ def scrape_data(scraper_choice, input1, input2=None):
48
  """
49
+ Hàm này nhận lựa chọn scrapercác input tương ứng.
50
  """
51
+ if scraper_choice == "Yellow Pages":
52
+ # Dùng Cách 1 (import hàm) nếu khả thi
53
+ if yp_scraper_available:
54
+ print(f"Chạy Yellow Pages với Keyword: {input1}, Location: {input2}")
55
+ scraped_data = parse_listing_function(input1, input2) # Gọi hàm đã import
56
+ # Định dạng kết quả từ list of dicts sang string
57
+ output_text = "Kết quả từ Yellow Pages:\n\n"
58
+ if not scraped_data or ("error" in scraped_data[0] if scraped_data else False):
59
+ return output_text + (scraped_data[0].get('error', 'Không có kết quả hoặc lỗi không xác định.') if scraped_data else 'Không có kết quả.')
60
 
61
+ for i, item in enumerate(scraped_data):
62
+ output_text += f"--- {i+1} ---\n"
63
+ # Thêm các key phù hợp với output của scraper yellowpages.py
64
+ output_text += f"Name: {item.get('business_name', 'N/A')}\n"
65
+ output_text += f"Phone: {item.get('telephone', 'N/A')}\n"
66
+ output_text += f"Address: {item.get('street', 'N/A')}, {item.get('locality', 'N/A')}\n"
67
+ output_text += f"Website: {item.get('website', 'N/A')}\n"
68
+ output_text += f"Rating: {item.get('rating', 'N/A')}\n"
69
+ output_text += f"URL: {item.get('url', 'N/A')}\n"
70
+ output_text += "------------\n"
71
+ return output_text
72
+ else:
73
+ # Dùng Cách 2 (subprocess) nếu Cách 1 không được hoặc script chỉ chạy CLI
74
+ print(f"Chạy Yellow Pages CLI với Keyword: {input1}, Location: {input2}")
75
+ return run_yellowpages_cli(input1, input2) # Gọi hàm chạy subprocess
76
 
77
+ # Thêm các lựa chọn scraper khác tại đây
78
+ # elif scraper_choice == "Google Search":
79
+ # # Cần import hàm hoặc chạy subprocess cho Google Search script
80
+ # # Và xử lý input/output riêng
81
+ # pass
82
+ # elif scraper_choice == "Amazon":
83
+ # # Cần import hàm hoặc chạy subprocess cho Amazon script
84
+ # # Và xử lý input/output riêng
85
+ # pass
86
 
87
+ else:
88
+ return "Vui lòng chọn một scraper."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
  # Tạo giao diện Gradio
91
+ with gr.Blocks() as demo:
92
+ gr.Markdown("# Demo Các Web Scraper")
93
+ gr.Markdown("Chọn một scraper và nhập các thông tin cần thiết.")
94
+
95
+ scraper_dropdown = gr.Dropdown(
96
+ ["Yellow Pages"], # Thêm tên các scraper khác vào list này
97
+ label="Chọn Scraper"
98
+ )
99
+
100
+ # Các input fields. Visibility thể được điều chỉnh dựa trên scraper_dropdown
101
+ input_keyword = gr.Textbox(label="Từ khóa")
102
+ input_location = gr.Textbox(label="Địa điểm (ví dụ: Boston,MA)")
103
+ # input_url = gr.Textbox(label="URL", visible=False) # Ví dụ input cho scraper khác
104
+
105
+ run_button = gr.Button("Chạy Scraper")
106
+
107
+ output_text = gr.Textbox(label="Kết quả", lines=20)
108
+
109
+ # Định nghĩa hành động khi nút được nhấn
110
+ # Cần truyền đúng số lượng và loại input cho hàm scrape_data
111
+ run_button.click(
112
+ scrape_data,
113
+ inputs=[scraper_dropdown, input_keyword, input_location], # Thêm input khác nếu cần
114
+ outputs=output_text
115
+ )
116
+
117
+ # Bạn có thể thêm các interaction để thay đổi hiển thị input
118
+ # dựa trên scraper_dropdown.change(...)
119
+
120
+ demo.launch()