-
Notifications
You must be signed in to change notification settings - Fork 0
/
summarization.py
204 lines (157 loc) · 6.46 KB
/
summarization.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import cohere
import streamlit as st
import os
import requests
import webbrowser
from bs4 import BeautifulSoup
import json
import re
co = cohere.Client(os.environ["COHERE_API_KEY"])
def formattingForSummarizer(text):
for each in text :
if (each == "'") :
text = text.replace(each, "")
if(each == "`"):
text = text.replace(each, "")
text = text.replace('\n', ' ').replace('\r', '').replace('\t', ' ')
return text
def summarizer (text):
CleanText = formattingForSummarizer(str(text))
# prompt_template = "Summarize the given content into 5 paragraph response of `MORE THAN 200 WORDS` each. The content is : " + ' ' + CleanText
# summarizer_prompt = "You are the manager of a hotel and you're task is to summarize the given content: that is the details of booking into the format needed for billing.. "
summarizer_prompt = "Summarize the given content. This is a conversation between a customer and hotel receptionist. Do not loose details like name, number, email, destination, check-in date, check-out date."
response = co.summarize(
text=CleanText,
length='long',
format='bullets',
model='summarize-xlarge',
additional_command= summarizer_prompt,
temperature=0.3,
)
print(response.summary)
return response.summary
# def generateKBase(largeData):
# rqdFormat = [
# {
# "title": " ",
# "snippet": " "
# },
# ]
# FormatPrompt = "You should extract the given details text: " + largeData +" into this \n: "+ " "+ str(rqdFormat) + "\n JSON FORMAT and populate the corresponding values from text : The snippet can contain the large amount of tokens.Don't shortent the content"
# response = co.generate(
# # text,
# model='command-nightly',
# prompt=FormatPrompt,
# temperature=0.3,
# return_likelihoods = None,
# # finish_reason= COMPLETE,
# # token_likelihoods= None,
# )
# print(response.generations[0].text)
# # sendAPIReg(response.generations[0].text)
def generateDetails(text):
JSONFormat = {
"name": "Ron Tennyson",
"number": 1234567890,
"email": "david@jojo.com",
"destination": "Kochi",
"check_in_date": "2023-02-6",
"check_out_date": "2023-02-10",
"unique_id": "ron890"
}
JSONFormatPrompt = f"""You should extract the given details from the text given below into the following JSON FORMAT:
Here is the JSON dta with dummy values for example:
{JSONFormat}
Populate corresponding values from text below, If you couldn't find all the answer to the fileds then do fill it with dummy values instead.
Use this format for datess instead: YYYY-MM-DD. UNIQUE ID is generated by taking the firt 3 letters of cutomer's name and last 3 digits of their phone number.
DO NOT LEAVE ANY FIELD BLANK AND NO OTHER OUTPUT REQUIRED.
Here is the text: {text}"""
response = co.generate(
# text,
model='command-nightly',
prompt=JSONFormatPrompt,
temperature=0.3,
return_likelihoods = None,
)
# st.write("The API Response to send : ")
# st.write(response.generations[0].text)
print(response.generations[0].text)
sendAPIReg(response.generations[0].text)
def fillEmptyFields(json_data):
required_fields = ["name", "number", "email", "destination", "check_in_date", "check_out_date", "unique_id"]
dummy_values = {
"name": "UNKNOWN",
"number":0000000,
"email": "unknown@example.com",
"destination": "UNKNOWN",
"check_in_date": "1900-01-01",
"check_out_date": "1900-01-01",
"unique_id": "UNKNOWN"
}
for field in required_fields:
if field not in json_data or not json_data[field] or json_data[field].strip() == "":
json_data[field] = dummy_values.get(field, "UNKNOWN")
return json_data
def ifJSONComplete(incoming_json):
required_fields = ["name", "number", "email", "destination", "check_in_date", "check_out_date", "unique_id"]
for field in required_fields:
if field not in incoming_json or incoming_json[field] in ["", " "]:
return False
print("________________JSON is complete____________")
return True
# Function to take only the JSON from input string
def getJSONReponse(input_string):
start_index = input_string.find('{')
end_index = input_string.find('}') + 1
json_string = input_string[start_index:end_index]
json_data = json.loads(json_string)
print("\nExtracted JSON: \n")
print(json.dumps(json_data, indent=2))
return json_data
def sendAPIReg(response_string):
payload = {}
if (ifJSONComplete(getJSONReponse(response_string))):
payload = getJSONReponse(response_string)
else :
print("_______JSON is not complete_______")
payload = fillEmptyFields(payload)
print("_______JSON completeddddd_______")
print(payload)
st.write("The API Response to send : \n", payload)
api_endpoint = "https://travel-llm-api.vercel.app/checkout/"
# Make a POST request to the API endpoint
response = requests.post(api_endpoint, data=payload)
# Check the status code of the response
if response.status_code == 201:
api_response = json.loads(response.text)
link = api_response.get("link", None)
print(link)
webbrowser.open(link)
# print("API Response: \n ", response.text)
else:
# API call failed, print the error status code and response content
print("API Error:", response.status_code, response.text)
def main():
text = """The customer wants to book a 1-bedroom suite for 2 days
The check-in date is from 13th September
The suite costs ₹12600 and comes with a king bed, executive lounge access, a shower/tub combination, and amenities like high-speed internet and 2 TVs.
Nothing was mentioned about extras."""
# generateKBase(data)
JSONFormat = {
"name": "TEST DATA ",
"number": 1234567890,
"email": "12321@gmail.com",
"destination": " ",
"check_in_date": "2002-02-6",
"check_out_date": "2002-02-6",
"unique_id": "abc123"
}
# sendAPIReg(JSONFormat)
# if ifJSONComplete(JSONFormat) :
# print("JSON is complete")
# else :
# print("JSON is not complete")
generateDetails(text)
# Add the summary
if __name__ == "__main__":
main()