Tulika2000 commited on
Commit
ae63fbe
·
verified ·
1 Parent(s): ca8c872

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -0
app.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """app.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1vaVKGg6ycx5H06dSgRVN0d5CzcJquou5
8
+ """
9
+
10
+ import os
11
+ from langchain import PromptTemplate, LLMChain
12
+ from googleapiclient.discovery import build
13
+ import gradio as gr
14
+ import html # For sanitizing user input
15
+
16
+ # Load API keys securely from Hugging Face Secrets
17
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
18
+ YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY")
19
+
20
+ if not GROQ_API_KEY or not YOUTUBE_API_KEY:
21
+ raise ValueError("❌ API keys are missing! Please add them in Hugging Face Secrets.")
22
+
23
+ # Initialize the Groq model
24
+ llm = ChatGroq(model="llama-3.3-70b-versatile", api_key=GROQ_API_KEY)
25
+
26
+ # Updated Prompt Template
27
+ prompt_template = PromptTemplate(
28
+ input_variables=["user_input", "age_range"],
29
+ template=(
30
+ "**{user_input}**\n\n"
31
+ "The user's selected age range is: **{age_range}**.\n\n"
32
+ "Use Chain-of-Thought (CoT) reasoning to analyze the situation in context with the age range, then provide "
33
+ "clear, actionable safety advice structured as follows:\n\n"
34
+ "**### 1. Safety Tips:**\n"
35
+ "- Offer **practical** and **actionable** steps to stay safe, tailored to the selected age range.\n"
36
+ "- Ensure the advice is **easy to follow** and **relevant** to the situation described.\n\n"
37
+ "**### 2. Self-Defense Techniques:**\n"
38
+ "- Provide simple, **age-appropriate self-defense methods** that are easy to implement.\n"
39
+ "- Focus on **safe** and **effective** techniques that suit the user's age and physical abilities.\n\n"
40
+ "**### 3. Resources:**\n"
41
+ "- Recommend **relevant YouTube videos** for learning and practical demonstrations of safety measures."
42
+ )
43
+ )
44
+
45
+ # Create the LLMChain
46
+ chain = LLMChain(llm=llm, prompt=prompt_template)
47
+
48
+ # Function to fetch YouTube videos with clickable links
49
+ def search_youtube_videos(query, max_results=2):
50
+ try:
51
+ youtube = build("youtube", "v3", developerKey=YOUTUBE_API_KEY)
52
+ request = youtube.search().list(
53
+ part="snippet", q=query, type="video", maxResults=max_results
54
+ )
55
+ response = request.execute()
56
+
57
+ video_html = ""
58
+ for item in response.get("items", []):
59
+ video_id = item["id"].get("videoId")
60
+ video_title = html.escape(item["snippet"].get("title", "Untitled"))
61
+ if video_id:
62
+ video_html += f'<p><a href="https://www.youtube.com/watch?v={video_id}" target="_blank">{video_title}</a></p>'
63
+
64
+ return video_html if video_html else "<p>No relevant videos found.</p>"
65
+ except Exception as e:
66
+ return f"<p>⚠️ Error fetching videos: {html.escape(str(e))}</p>"
67
+
68
+ # Function to get YouTube links based on age range
69
+ def get_youtube_links(age_range):
70
+ queries = {
71
+ "0-6 (Toddler)": "toddler safety self-defense techniques",
72
+ "7-13 (Child)": "self-defense for kids",
73
+ "15-30 (Teenager to Young Adult)": "basic self-defense techniques for teens",
74
+ "30+ (Adult)": "advanced self-defense techniques for adults"
75
+ }
76
+ return search_youtube_videos(queries.get(age_range, "self-defense safety tips"), max_results=2)
77
+
78
+ # Safety Advice Function
79
+ def safety_advice(user_input, age_range):
80
+ if not user_input.strip():
81
+ return "⚠️ Please enter a situation to receive advice.", "<p></p>" # Empty HTML for videos
82
+
83
+ response = chain.run(user_input=user_input, age_range=age_range)
84
+ links_html = get_youtube_links(age_range)
85
+
86
+ return f"{response}", links_html # Markdown for text, HTML for videos
87
+
88
+ # Function to clear fields
89
+ def clear_fields():
90
+ return "", "30+ (Adult)", "", ""
91
+
92
+ # Gradio Interface
93
+ with gr.Blocks() as app:
94
+ gr.Markdown("# 🛡️ SheGuard: Personal Safety Advisor 🛡️\n\n💡 Enter a situation where you feel unsafe, and receive expert safety advice tailored to your age range.")
95
+
96
+ with gr.Row():
97
+ situation_input = gr.Textbox(label="Describe Your Situation", placeholder="E.g., I noticed someone suspicious near my house.")
98
+ age_range_input = gr.Radio([
99
+ "0-6 (Toddler)", "7-13 (Child)", "15-30 (Teenager to Young Adult)", "30+ (Adult)"
100
+ ], label="Select Your Age Range", value="30+ (Adult)")
101
+
102
+ advice_output = gr.Markdown()
103
+ video_output = gr.HTML() # Using HTML for active YouTube links
104
+
105
+ with gr.Row():
106
+ generate_button = gr.Button("Get Safety Advice")
107
+ clear_button = gr.Button("Clear")
108
+
109
+ generate_button.click(safety_advice, inputs=[situation_input, age_range_input], outputs=[advice_output, video_output])
110
+ clear_button.click(clear_fields, inputs=[], outputs=[situation_input, age_range_input, advice_output, video_output])
111
+
112
+ app.launch(share = True)