sivan26 commited on
Commit
22d1514
·
verified ·
1 Parent(s): c114913

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -23
app.py CHANGED
@@ -4,18 +4,23 @@ import random
4
  import time
5
  from transformers import pipeline
6
 
 
7
  classifier = pipeline("zero-shot-classification", model="valhalla/distilbart-mnli-12-3")
8
- random_topics = ["cats", "space", "chocolate", "Egypt", "Leonardo da Vinci",
9
- "volcanoes", "Tokyo", "honeybees", "quantum physics", "orcas"]
10
 
11
- def get_wikipedia_facts(topic):
12
- # your existing function here unchanged...
13
- # (copy-paste your original function)
 
 
14
 
 
 
15
  if not topic.strip():
16
  return "Please enter a topic or use 'Surprise me!'", None, None
17
 
18
- headers = {"User-Agent": "RandomFactApp/3.0 (https://huggingface.co/spaces/yourname) Python requests"}
 
 
19
 
20
  search_url = "https://en.wikipedia.org/w/api.php"
21
  search_params = {
@@ -27,6 +32,7 @@ def get_wikipedia_facts(topic):
27
  }
28
 
29
  try:
 
30
  search_response = requests.get(search_url, params=search_params, headers=headers)
31
  time.sleep(0.3)
32
  search_data = search_response.json()
@@ -37,6 +43,7 @@ def get_wikipedia_facts(topic):
37
 
38
  best_title = search_hits[0]["title"]
39
 
 
40
  extract_params = {
41
  "action": "query",
42
  "format": "json",
@@ -59,6 +66,7 @@ def get_wikipedia_facts(topic):
59
  if not extract_text:
60
  return f"Sorry, no extract found for '{topic}'.", None, None
61
 
 
62
  sentences = [s.strip() for s in extract_text.replace("\n", " ").split(". ") if s.strip()]
63
  if not sentences:
64
  return f"Sorry, no facts available for '{topic}'.", None, None
@@ -67,8 +75,10 @@ def get_wikipedia_facts(topic):
67
  facts = [fact if fact.endswith(".") else fact + "." for fact in facts]
68
  facts_text = "\n\n".join(f"💡 {fact}" for fact in facts)
69
 
 
70
  image_url = page.get("thumbnail", {}).get("source", None)
71
 
 
72
  labels = ["history", "science", "technology", "art", "geography", "biology", "music", "sports", "politics"]
73
  classification = classifier(topic, labels)
74
  top_label = classification["labels"][0]
@@ -81,29 +91,34 @@ def get_wikipedia_facts(topic):
81
  print("Error:", e)
82
  return "Oops! Something went wrong while fetching your facts.", None, None
83
 
 
84
  def surprise_topic(_):
85
  topic = random.choice(random_topics)
86
  return get_wikipedia_facts(topic)
87
 
 
88
  with gr.Blocks() as demo:
89
 
90
- # Background box with soft clouds image
91
- with gr.Box(
92
- elem_id="background-box",
93
- style={
94
- "background-image": "url('https://images.unsplash.com/photo-1506744038136-46273834b3fb?auto=format&fit=crop&w=1470&q=80')",
95
- "background-size": "cover",
96
- "background-position": "center",
97
- "position": "fixed",
98
- "top": "0",
99
- "left": "0",
100
- "width": "100vw",
101
- "height": "100vh",
102
- "z-index": "-1",
103
- "filter": "brightness(0.85)"
104
  }
105
- ):
106
- pass
 
 
 
 
107
 
108
  gr.Markdown("""
109
  # 🌍 Smart Wikipedia Fact Finder
@@ -130,11 +145,12 @@ with gr.Blocks() as demo:
130
  with gr.Column():
131
  image_output = gr.Image(label="🖼️ Related Image")
132
 
 
133
  topic_input.submit(get_wikipedia_facts, inputs=topic_input, outputs=[facts_output, image_output, classification_output])
134
  surprise_button.click(surprise_topic, inputs=None, outputs=[facts_output, image_output, classification_output])
135
 
 
136
  if __name__ == "__main__":
137
  demo.launch()
138
 
139
-
140
 
 
4
  import time
5
  from transformers import pipeline
6
 
7
+ # Load the zero-shot classification pipeline
8
  classifier = pipeline("zero-shot-classification", model="valhalla/distilbart-mnli-12-3")
 
 
9
 
10
+ # List of random topics for the "Surprise me" button
11
+ random_topics = [
12
+ "cats", "space", "chocolate", "Egypt", "Leonardo da Vinci",
13
+ "volcanoes", "Tokyo", "honeybees", "quantum physics", "orcas"
14
+ ]
15
 
16
+ # Main function: get Wikipedia extract, image, and classify topic
17
+ def get_wikipedia_facts(topic):
18
  if not topic.strip():
19
  return "Please enter a topic or use 'Surprise me!'", None, None
20
 
21
+ headers = {
22
+ "User-Agent": "RandomFactApp/3.0 (https://huggingface.co/spaces/yourname) Python requests"
23
+ }
24
 
25
  search_url = "https://en.wikipedia.org/w/api.php"
26
  search_params = {
 
32
  }
33
 
34
  try:
35
+ # Step 1: Search Wikipedia
36
  search_response = requests.get(search_url, params=search_params, headers=headers)
37
  time.sleep(0.3)
38
  search_data = search_response.json()
 
43
 
44
  best_title = search_hits[0]["title"]
45
 
46
+ # Step 2: Get page extract and image
47
  extract_params = {
48
  "action": "query",
49
  "format": "json",
 
66
  if not extract_text:
67
  return f"Sorry, no extract found for '{topic}'.", None, None
68
 
69
+ # Format extract into short facts
70
  sentences = [s.strip() for s in extract_text.replace("\n", " ").split(". ") if s.strip()]
71
  if not sentences:
72
  return f"Sorry, no facts available for '{topic}'.", None, None
 
75
  facts = [fact if fact.endswith(".") else fact + "." for fact in facts]
76
  facts_text = "\n\n".join(f"💡 {fact}" for fact in facts)
77
 
78
+ # Get image URL
79
  image_url = page.get("thumbnail", {}).get("source", None)
80
 
81
+ # Zero-shot classification
82
  labels = ["history", "science", "technology", "art", "geography", "biology", "music", "sports", "politics"]
83
  classification = classifier(topic, labels)
84
  top_label = classification["labels"][0]
 
91
  print("Error:", e)
92
  return "Oops! Something went wrong while fetching your facts.", None, None
93
 
94
+ # Surprise topic function
95
  def surprise_topic(_):
96
  topic = random.choice(random_topics)
97
  return get_wikipedia_facts(topic)
98
 
99
+ # Gradio UI layout
100
  with gr.Blocks() as demo:
101
 
102
+ # Background image injected via HTML (safe for Hugging Face)
103
+ gr.HTML("""
104
+ <style>
105
+ .cloud-bg {
106
+ background: url('https://images.unsplash.com/photo-1506744038136-46273834b3fb?auto=format&fit=crop&w=1470&q=80') no-repeat center center fixed;
107
+ background-size: cover;
108
+ position: fixed;
109
+ top: 0;
110
+ left: 0;
111
+ width: 100vw;
112
+ height: 100vh;
113
+ z-index: -1;
114
+ opacity: 0.8;
 
115
  }
116
+ .gradio-container {
117
+ background: transparent !important;
118
+ }
119
+ </style>
120
+ <div class="cloud-bg"></div>
121
+ """)
122
 
123
  gr.Markdown("""
124
  # 🌍 Smart Wikipedia Fact Finder
 
145
  with gr.Column():
146
  image_output = gr.Image(label="🖼️ Related Image")
147
 
148
+ # Link functions to inputs
149
  topic_input.submit(get_wikipedia_facts, inputs=topic_input, outputs=[facts_output, image_output, classification_output])
150
  surprise_button.click(surprise_topic, inputs=None, outputs=[facts_output, image_output, classification_output])
151
 
152
+ # Run the app
153
  if __name__ == "__main__":
154
  demo.launch()
155
 
 
156