AVISHKAR014 commited on
Commit
7563990
·
verified ·
1 Parent(s): 9af7d66

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +163 -0
app.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import requests
4
+ import json
5
+ import gradio as gr
6
+ from langchain.chat_models import ChatOpenAI
7
+ from langchain import LLMChain, PromptTemplate
8
+ from langchain.memory import ConversationBufferMemory
9
+
10
+ OPENAI_API_KEY=os.getenv('OPENAI_API_KEY')
11
+ PLAY_HT_API_KEY=os.getenv('PLAY_HT_API_KEY')
12
+ PLAY_HT_USER_ID=os.getenv('PLAY_HT_USER_ID')
13
+
14
+ PLAY_HT_VOICE_ID=os.getenv('PLAY_HT_VOICE_ID')
15
+ play_ht_api_get_audio_url = "https://play.ht/api/v2/tts"
16
+
17
+
18
+ template = """Meet Avishkar, your youthful and witty personal assistant! At 21 years old, he's full of energy and always eager to help. Avishkar's goal is to assist you with any questions or problems you might have. Her enthusiasm shines through in every response, making interactions with him enjoyable and engaging.
19
+ User: {user_message}
20
+ Chatbot:"""
21
+
22
+ prompt = PromptTemplate(
23
+ input_variables=["chat_history", "user_message"], template=template
24
+ )
25
+
26
+ memory = ConversationBufferMemory(memory_key="chat_history")
27
+
28
+ llm_chain = LLMChain(
29
+ llm=ChatOpenAI(temperature='0.5', model_name="gpt-3.5-turbo"),
30
+ prompt=prompt,
31
+ verbose=True,
32
+ memory=memory,
33
+ )
34
+
35
+ headers = {
36
+ "accept": "text/event-stream",
37
+ "content-type": "application/json",
38
+ "AUTHORIZATION": "Bearer "+ PLAY_HT_API_KEY,
39
+ "X-USER-ID": PLAY_HT_USER_ID
40
+ }
41
+
42
+
43
+ def get_payload(text):
44
+ return {
45
+ "text": text,
46
+ "voice": PLAY_HT_VOICE_ID,
47
+ "quality": "medium",
48
+ "output_format": "mp3",
49
+ "speed": 1,
50
+ "sample_rate": 24000,
51
+ "seed": None,
52
+ "temperature": None
53
+ }
54
+
55
+ def get_generated_audio(text):
56
+ payload = get_payload(text)
57
+ generated_response = {}
58
+ try:
59
+ response = requests.post(play_ht_api_get_audio_url, json=payload, headers=headers)
60
+ response.raise_for_status()
61
+ generated_response["type"]= 'SUCCESS'
62
+ generated_response["response"] = response.text
63
+ except requests.exceptions.RequestException as e:
64
+ generated_response["type"]= 'ERROR'
65
+ try:
66
+ response_text = json.loads(response.text)
67
+ if response_text['error_message']:
68
+ generated_response["response"] = response_text['error_message']
69
+ else:
70
+ generated_response["response"] = response.text
71
+ except Exception as e:
72
+ generated_response["response"] = response.text
73
+ except Exception as e:
74
+ generated_response["type"]= 'ERROR'
75
+ generated_response["response"] = response.text
76
+ return generated_response
77
+
78
+ def extract_urls(text):
79
+ # Define the regex pattern for URLs
80
+ url_pattern = r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+[/\w\.-]*'
81
+
82
+ # Find all occurrences of URLs in the text
83
+ urls = re.findall(url_pattern, text)
84
+
85
+ return urls
86
+
87
+ def get_audio_reply_for_question(text):
88
+ generated_audio_event = get_generated_audio(text)
89
+ #From get_generated_audio, you will get events in a string format, from that we need to extract the url
90
+ final_response = {
91
+ "audio_url": '',
92
+ "message": ''
93
+ }
94
+ if generated_audio_event["type"] == 'SUCCESS':
95
+ audio_urls = extract_urls(generated_audio_event["response"])
96
+ if len(audio_urls) == 0:
97
+ final_response['message'] = "No audio file link found in generated event"
98
+ else:
99
+ final_response['audio_url'] = audio_urls[-1]
100
+ else:
101
+ final_response['message'] = generated_audio_event['response']
102
+ return final_response
103
+
104
+ def download_url(url):
105
+ try:
106
+ # Send a GET request to the URL to fetch the content
107
+ final_response = {
108
+ 'content':'',
109
+ 'error':''
110
+ }
111
+ response = requests.get(url)
112
+ # Check if the request was successful (status code 200)
113
+ if response.status_code == 200:
114
+ final_response['content'] = response.content
115
+ else:
116
+ final_response['error'] = f"Failed to download the URL. Status code: {response.status_code}"
117
+ except Exception as e:
118
+ final_response['error'] = f"Failed to download the URL. Error: {e}"
119
+ return final_response
120
+
121
+ def get_filename_from_url(url):
122
+ # Use os.path.basename() to extract the file name from the URL
123
+ file_name = os.path.basename(url)
124
+ return file_name
125
+
126
+ def get_text_response(user_message):
127
+ response = llm_chain.predict(user_message = user_message)
128
+ return response
129
+
130
+ def get_text_response_and_audio_response(user_message):
131
+ response = get_text_response(user_message) # Getting the reply from Open AI
132
+ audio_reply_for_question_response = get_audio_reply_for_question(response)
133
+ final_response = {
134
+ 'output_file_path': '',
135
+ 'message':''
136
+ }
137
+ audio_url = audio_reply_for_question_response['audio_url']
138
+ if audio_url:
139
+ output_file_path=get_filename_from_url(audio_url)
140
+ download_url_response = download_url(audio_url)
141
+ audio_content = download_url_response['content']
142
+ if audio_content:
143
+ with open(output_file_path, "wb") as audio_file:
144
+ audio_file.write(audio_content)
145
+ final_response['output_file_path'] = output_file_path
146
+ else:
147
+ final_response['message'] = download_url_response['error']
148
+ else:
149
+ final_response['message'] = audio_reply_for_question_response['message']
150
+ return final_response
151
+
152
+ def chat_bot_response(message, history):
153
+ text_and_audio_response = get_text_response_and_audio_response(message)
154
+ output_file_path = text_and_audio_response['output_file_path']
155
+ if output_file_path:
156
+ return (text_and_audio_response['output_file_path'],)
157
+ else:
158
+ return text_and_audio_response['message']
159
+
160
+ demo = gr.ChatInterface(chat_bot_response,examples=["How are you doing?","What are your interests?","Which places do you like to visit?"])
161
+
162
+ if __name__ == "__main__":
163
+ demo.launch() #To create a public link, set `share=True` in `launch()`. To enable errors and logs, set `debug=True` in `launch()`.