Abbas0786 commited on
Commit
78ad284
1 Parent(s): 0682d23

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -52
app.py CHANGED
@@ -1,64 +1,93 @@
1
- import streamlit as st
 
 
 
 
2
  import requests
3
  from groq import Groq
 
4
 
5
- # Set up API keys and URLs
6
- # Use your OpenWeatherMap API key
7
- openweather_api_key = "aa4db8152e46c2f3fb19fad5d58a0ed8ddssd"
8
- openweather_api_url = "https://api.openweathermap.org/data/2.5/weather"
9
 
10
- # Set up Groq API
11
- groq_api_key = "gsk_loI5Z6fHhtPZo25YmryjWGdyb3FYdfrw1oxGVCfZkwXRE79BAgHCO7c"
12
- client = Groq(api_key=groq_api_key)
 
13
 
14
- # Streamlit UI
15
- st.title("Real-time Weather App")
16
 
17
- # City input
18
- city = st.text_input("Enter city name")
19
 
20
- # Weather data display
21
- if city:
22
- # OpenWeatherMap API request
23
- params = {
24
- "q": city,
25
- "appid": openweather_api_key,
26
- "units": "metric" # For temperature in Celsius; use "imperial" for Fahrenheit
27
- }
28
-
29
  try:
30
- response = requests.get(openweather_api_url, params=params)
31
- response.raise_for_status() # Will raise an HTTPError for bad responses
32
-
 
 
 
 
 
 
33
  weather_data = response.json()
 
 
 
 
 
 
 
 
 
 
34
 
35
- if weather_data.get("cod") != 200:
36
- st.write(f"Error fetching weather data: {weather_data.get('message', 'Unknown error')}")
 
 
 
 
 
 
 
37
  else:
38
- # Display weather data
39
- st.write("Current Weather:")
40
- st.write(f"City: {weather_data['name']}, {weather_data['sys']['country']}")
41
- st.write(f"Temperature: {weather_data['main']['temp']}°C")
42
- st.write(f"Weather: {weather_data['weather'][0]['description'].capitalize()}")
43
- st.write(f"Humidity: {weather_data['main']['humidity']}%")
44
- st.write(f"Wind Speed: {weather_data['wind']['speed']} m/s")
45
-
46
- except requests.exceptions.RequestException as e:
47
- st.write(f"Error fetching weather data: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
- # Remove Groq API request and response handling
50
- # try:
51
- # chat_completion = client.chat.completions.create(
52
- # messages=[
53
- # {
54
- # "role": "user",
55
- # "content": "Explain the importance of fast language models",
56
- # }
57
- # ],
58
- # model="llama3-8b-8192",
59
- # )
60
- # st.write("Groq AI Response:")
61
- # st.write(chat_completion.choices[0].message.content)
62
-
63
- # except Exception as e:
64
- # st.write(f"Error fetching Groq data: {e}")
 
1
+ import os
2
+ import gradio as gr
3
+ import whisper
4
+ from gtts import gTTS
5
+ import io
6
  import requests
7
  from groq import Groq
8
+ import time
9
 
10
+ # Ensure GROQ_API_KEY and OpenWeather API key are defined
11
+ GROQ_API_KEY = "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"
12
+ OPENWEATHER_API_KEY = "aa4db8152e46c2f3fb19fad5d58a0ed8"
13
+ OPENWEATHER_URL = "https://api.openweathermap.org/data/2.5/weather"
14
 
15
+ if not GROQ_API_KEY:
16
+ raise ValueError("GROQ_API_KEY is not set in environment variables.")
17
+ if not OPENWEATHER_API_KEY:
18
+ raise ValueError("OPENWEATHER_API_KEY is not set in environment variables.")
19
 
20
+ # Initialize the Groq client
21
+ client = Groq(api_key=GROQ_API_KEY)
22
 
23
+ # Load the Whisper model
24
+ model = whisper.load_model("base") # Ensure this model supports Urdu; otherwise, choose a suitable model
25
 
26
+ def fetch_weather():
 
 
 
 
 
 
 
 
27
  try:
28
+ response = requests.get(
29
+ OPENWEATHER_URL,
30
+ params={
31
+ 'q': 'London', # Change to dynamic city name as needed
32
+ 'appid': OPENWEATHER_API_KEY,
33
+ 'units': 'metric'
34
+ }
35
+ )
36
+ response.raise_for_status()
37
  weather_data = response.json()
38
+ temp = weather_data['main']['temp']
39
+ weather_description = weather_data['weather'][0]['description']
40
+ return f"Current temperature is {temp}°C with {weather_description}."
41
+ except Exception as e:
42
+ return f"Unable to fetch weather data: {e}"
43
+
44
+ def process_audio(file_path):
45
+ try:
46
+ # Load the audio file
47
+ audio = whisper.load_audio(file_path)
48
 
49
+ # Transcribe the audio using Whisper (specify language if needed)
50
+ result = model.transcribe(audio, language="ur") # Specify 'ur' for Urdu
51
+ text = result["text"]
52
+
53
+ # Check if the text contains any weather-related keywords
54
+ weather_keywords = ['weather', 'temperature', 'climate', 'forecast']
55
+ if any(keyword in text.lower() for keyword in weather_keywords):
56
+ weather_info = fetch_weather()
57
+ response_message = f"The weather update: {weather_info}"
58
  else:
59
+ # Generate a response in Urdu using Groq
60
+ chat_completion = client.chat.completions.create(
61
+ messages=[{"role": "user", "content": text}],
62
+ model="gemma2-9b-it", # Ensure this model can handle Urdu
63
+ )
64
+ # Access the response using dot notation
65
+ response_message = chat_completion.choices[0].message.content.strip()
66
+
67
+ # Convert the response text to Urdu speech
68
+ tts = gTTS(response_message, lang='ur') # Specify language 'ur' for Urdu
69
+ response_audio_io = io.BytesIO()
70
+ tts.write_to_fp(response_audio_io) # Save the audio to the BytesIO object
71
+ response_audio_io.seek(0)
72
+
73
+ # Generate a unique filename
74
+ response_audio_path = "response_" + str(int(time.time())) + ".mp3"
75
+
76
+ # Save audio to a file
77
+ with open(response_audio_path, "wb") as audio_file:
78
+ audio_file.write(response_audio_io.getvalue())
79
+
80
+ # Return the response text and the path to the saved audio file
81
+ return response_message, response_audio_path
82
+
83
+ except Exception as e:
84
+ return f"An error occurred: {e}", None
85
+
86
+ iface = gr.Interface(
87
+ fn=process_audio,
88
+ inputs=gr.Audio(type="filepath"), # Use type="filepath"
89
+ outputs=[gr.Textbox(label="Response Text (Urdu)"), gr.Audio(label="Response Audio (Urdu)")],
90
+ live=True # Set to False if you do not need real-time updates
91
+ )
92
 
93
+ iface.launch()