sagar007 commited on
Commit
07b96fa
·
verified ·
1 Parent(s): 1589699

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -80
app.py CHANGED
@@ -1,92 +1,100 @@
1
  import gradio as gr
2
- import numpy as np
3
- from PIL import Image
 
 
 
 
4
  import random
 
 
5
 
6
- # Game state variables
7
- ship_position = 50 # Ship's horizontal position (0-100)
8
- enemies = [] # List of enemy positions
9
- score = 0
 
 
10
 
11
- # Function to generate a simple game screen as an image
12
- def create_game_screen(ship_pos, enemy_list, score):
13
- # Create a blank 200x200 image (black background)
14
- img = np.zeros((200, 200, 3), dtype=np.uint8)
15
-
16
- # Draw ship (white rectangle) at the bottom
17
- ship_y = 180
18
- img[ship_y:ship_y+10, max(0, ship_pos-5):min(200, ship_pos+5)] = [255, 255, 255]
19
-
20
- # Draw enemies (red squares)
21
- for enemy_x, enemy_y in enemy_list:
22
- img[max(0, enemy_y-5):min(200, enemy_y+5), max(0, enemy_x-5):min(200, enemy_x+5)] = [255, 0, 0]
23
-
24
- # Convert to PIL Image for Gradio
25
- return Image.fromarray(img), f"Score: {score}"
26
 
27
- # Function to update game state based on user action
28
- def update_game(action):
29
- global ship_position, enemies, score
30
-
31
- # Move ship
32
- if action == "Move Left" and ship_position > 10:
33
- ship_position -= 10
34
- elif action == "Move Right" and ship_position < 190:
35
- ship_position += 10
36
-
37
- # Shooting logic
38
- elif action == "Shoot":
39
- for i, (enemy_x, enemy_y) in enumerate(enemies[:]):
40
- if abs(enemy_x - ship_position) < 15 and enemy_y > 150: # Rough hit detection
41
- enemies.pop(i)
42
- score += 10
43
- break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
- # Spawn new enemies randomly
46
- if random.random() < 0.3: # 30% chance to spawn an enemy
47
- enemies.append([random.randint(0, 200), 0])
48
-
49
- # Move enemies down
50
- for enemy in enemies[:]:
51
- enemy[1] += 10
52
- if enemy[1] > 200: # Remove enemies that go off-screen
53
- enemies.remove(enemy)
54
-
55
- # Generate updated game screen
56
- return create_game_screen(ship_position, enemies, score)
57
-
58
- # Reset game state
59
- def reset_game():
60
- global ship_position, enemies, score
61
- ship_position = 50
62
- enemies = []
63
- score = 0
64
- return create_game_screen(ship_position, enemies, score)
65
 
66
  # Gradio interface
67
- with gr.Blocks(title="Blastar 1984 Simulator") as demo:
68
- gr.Markdown("# Blastar 1984 Simulator")
69
- gr.Markdown("A simplified version of Elon Musk's 1984 game. Move your ship and shoot enemies!")
70
-
71
- # Display game screen and score
72
- output_image = gr.Image(label="Game Screen")
73
- output_text = gr.Textbox(label="Score")
74
-
75
- # Buttons for controls
76
- with gr.Row():
77
- btn_left = gr.Button("Move Left")
78
- btn_right = gr.Button("Move Right")
79
- btn_shoot = gr.Button("Shoot")
80
- btn_reset = gr.Button("Reset Game")
81
 
82
- # Event handlers
83
- btn_left.click(fn=update_game, inputs=gr.State(value="Move Left"), outputs=[output_image, output_text])
84
- btn_right.click(fn=update_game, inputs=gr.State(value="Move Right"), outputs=[output_image, output_text])
85
- btn_shoot.click(fn=update_game, inputs=gr.State(value="Shoot"), outputs=[output_image, output_text])
86
- btn_reset.click(fn=reset_game, inputs=None, outputs=[output_image, output_text])
87
 
88
- # Initial state
89
- demo.load(fn=reset_game, inputs=None, outputs=[output_image, output_text])
 
 
 
90
 
91
- # Launch the app (Hugging Face handles this automatically)
92
  demo.launch()
 
1
  import gradio as gr
2
+ import requests
3
+ from bs4 import BeautifulSoup
4
+ import pandas as pd
5
+ from selenium import webdriver
6
+ from selenium.webdriver.chrome.options import Options
7
+ import csv
8
  import random
9
+ import time
10
+ import os
11
 
12
+ # List of user agents to avoid bot detection
13
+ USER_AGENTS = [
14
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
15
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36",
16
+ "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0"
17
+ ]
18
 
19
+ # Function to initialize Selenium driver (headless)
20
+ def get_driver():
21
+ chrome_options = Options()
22
+ chrome_options.add_argument("--headless") # Run in headless mode
23
+ chrome_options.add_argument("--no-sandbox")
24
+ chrome_options.add_argument("--disable-dev-shm-usage")
25
+ driver = webdriver.Chrome(options=chrome_options)
26
+ return driver
 
 
 
 
 
 
 
27
 
28
+ # Function to scrape Flipkart laptop data
29
+ def scrape_flipkart(url):
30
+ try:
31
+ # Set up Selenium driver
32
+ driver = get_driver()
33
+ headers = {"User-Agent": random.choice(USER_AGENTS)}
34
+
35
+ # Load the page
36
+ driver.get(url)
37
+ time.sleep(5) # Wait for JavaScript to load content
38
+
39
+ # Get page source and parse with BeautifulSoup
40
+ soup = BeautifulSoup(driver.page_source, "html.parser")
41
+ driver.quit() # Close the driver
42
+
43
+ # Lists to store scraped data
44
+ products = []
45
+ prices = []
46
+ ratings = []
47
+
48
+ # Find laptop items (adjust class names based on Flipkart's HTML structure)
49
+ items = soup.find_all("div", class_="_1AtVbE") # Parent div for each product
50
+ for item in items:
51
+ # Product name
52
+ name_tag = item.find("div", class_="_4rR01T")
53
+ name = name_tag.text.strip() if name_tag else "N/A"
54
+
55
+ # Price
56
+ price_tag = item.find("div", class_="_30jeq3")
57
+ price = price_tag.text.strip() if price_tag else "N/A"
58
+
59
+ # Rating
60
+ rating_tag = item.find("div", class_="_3LWZlK")
61
+ rating = rating_tag.text.strip() if rating_tag else "N/A"
62
+
63
+ if name != "N/A": # Only append valid entries
64
+ products.append(name)
65
+ prices.append(price)
66
+ ratings.append(rating)
67
+
68
+ # Create DataFrame
69
+ df = pd.DataFrame({
70
+ "Product Name": products,
71
+ "Price": prices,
72
+ "Rating": ratings
73
+ })
74
+
75
+ # Save to CSV
76
+ csv_path = "flipkart_laptops.csv"
77
+ df.to_csv(csv_path, index=False, encoding="utf-8")
78
+
79
+ return f"Scraped {len(products)} laptops successfully!", csv_path
80
 
81
+ except Exception as e:
82
+ return f"Error: {str(e)}", None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
  # Gradio interface
85
+ with gr.Blocks(title="Flipkart Laptop Scraper") as demo:
86
+ gr.Markdown("# Flipkart Laptop Scraper")
87
+ gr.Markdown("Enter a Flipkart laptop category URL to scrape data and download as CSV.")
 
 
 
 
 
 
 
 
 
 
 
88
 
89
+ url_input = gr.Textbox(label="Flipkart URL", placeholder="e.g., https://www.flipkart.com/laptops/pr?sid=6bo,b5g")
90
+ scrape_btn = gr.Button("Scrape Data")
91
+ output_text = gr.Textbox(label="Status")
92
+ output_file = gr.File(label="Download CSV")
 
93
 
94
+ scrape_btn.click(
95
+ fn=scrape_flipkart,
96
+ inputs=url_input,
97
+ outputs=[output_text, output_file]
98
+ )
99
 
 
100
  demo.launch()