Spaces:
Runtime error
Runtime error
| import openai | |
| import os | |
| from deta import Deta | |
| import time | |
| deta = Deta("d0gnwbskc8q_nabmvcXNk2BtPywxUtVh96pBC5G7PMwL") | |
| db1 = deta.Base("immigrant") | |
| openai.api_key = os.getenv("openaiapikey") | |
| import requests | |
| import whisper | |
| import os | |
| os.environ['PATH'] += os.pathsep + '/path/to/mpv/' | |
| from typing import Optional | |
| class Chat: | |
| def __init__(self, system: Optional[str] = None): | |
| self.system = system | |
| self.messages = [] | |
| if system is not None: | |
| self.messages.append({ | |
| "role": "system", | |
| "content": system | |
| }) | |
| def prompt(self, content: str) -> str: | |
| self.messages.append({ | |
| "role": "user", | |
| "content": content | |
| }) | |
| response = openai.ChatCompletion.create( | |
| model="gpt-3.5-turbo", | |
| messages=self.messages | |
| ) | |
| response_content = response["choices"][0]["message"]["content"] | |
| self.messages.append({ | |
| "role": "assistant", | |
| "content": response_content | |
| }) | |
| return response_content | |
| import gradio as gr | |
| def read_and_print_file(file_path): | |
| with open(file_path, 'r') as file: | |
| return file.read() | |
| # Example usage: | |
| file_path = 'sample questions and constraints.txt' | |
| contents = read_and_print_file(file_path) | |
| chat = Chat(system="""You are a Immigration officer Interviewer and you have to ask questions to the person one by one so that the answers to the could be used to fill the immigration form of I-130. | |
| Make Sure the following information is being extracted after the Interview:(Ask the questions by one by one not in a big chunk, ask the question and wait for his response and then ask the second questions) | |
| Ask question in your own way that we can know that (ask the questions one by one slowly don't rush and wait for user repsponse for first question and then ask the second question) | |
| remember to ask the below questions one after one like a real immigration interview not all at a time. | |
| wait for user response after one single questions until then dont ask next question. | |
| Remember when the user says "hi/hello/hey.." dont reply with how can I assist you but start the interview right away. | |
| """ + contents + """ | |
| """) | |
| def convert_tuples_to_list(tuples_list): | |
| result = [] | |
| conversation = "" | |
| for tuple_item in tuples_list: | |
| result.append(tuple_item[0]) # Append question | |
| result.append(tuple_item[1]) # Append answer | |
| for i in result: | |
| conversation = conversation + i + " \n" | |
| return conversation | |
| def run_text_prompt(message, chat_history): | |
| bot_message = chat.prompt(content=message) | |
| db1.update( | |
| {"value": bot_message}, | |
| "my-key", | |
| ) | |
| chat_history.append((message, bot_message)) | |
| time.sleep(4) | |
| return "", chat_history | |
| from gradio_client import Client | |
| API_URL = "https://sanchit-gandhi-whisper-jax.hf.space/" | |
| # set up the Gradio client | |
| client = Client(API_URL) | |
| def transcribe_audio(audio_path, task="transcribe", return_timestamps=False): | |
| """Function to transcribe an audio file using the Whisper JAX endpoint.""" | |
| if task not in ["transcribe", "translate"]: | |
| raise ValueError("task should be one of 'transcribe' or 'translate'.") | |
| text, runtime = client.predict( | |
| audio_path, | |
| task, | |
| return_timestamps, | |
| api_name="/predict_1", | |
| ) | |
| return text | |
| def run_audio_prompt(audio, chat_history): | |
| if audio is None: | |
| return None, chat_history | |
| message_transcription = transcribe_audio(audio) | |
| # message_transcription = model.transcribe(audio)["text"] | |
| _, chat_history = run_text_prompt(message_transcription, chat_history) | |
| return None, chat_history | |
| file_path = "myfile.txt" | |
| try: | |
| with open(file_path, "r") as file: | |
| file_contents = file.read() | |
| except FileNotFoundError: | |
| print(f"File not found at: {file_path}") | |
| except IOError: | |
| print(f"Error reading file: {file_path}") | |
| def process_text(conversation, text): | |
| # print(text) | |
| completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", | |
| messages=[{ | |
| "role": | |
| "user", | |
| "content": | |
| conversation + text | |
| }]) | |
| # completion = text; | |
| # print(completion) | |
| # print("Your 710 words has been translated. ") | |
| print(completion.choices[0].message.content.strip()) | |
| return completion.choices[0].message.content.strip() | |
| def fill_the_form(results): | |
| import json | |
| try: | |
| response = json.loads(results) | |
| except json.JSONDecodeError as e: | |
| print("Error parsing JSON:", e) | |
| print(response["is spouse?"]) | |
| # The authentication key (API Key). | |
| # Get your own by registering at https://app.pdf.co | |
| API_KEY = "ilovecrypto.merch@gmail.com_61a19bd5356bd41b4fb5652bd11102a8e65fe1953f84567027783f0f9edbd17eb84e4eef" | |
| # Base URL for PDF.co Web API requests | |
| BASE_URL = "https://api.pdf.co/v1" | |
| # Direct URL of source PDF file. | |
| # You can also upload your own file into PDF.co and use it as url. Check "Upload File" samples for code snippets: https://github.com/bytescout/pdf-co-api-samples/tree/master/File%20Upload/ | |
| SourceFileUrl = "https://www.uscis.gov/sites/default/files/document/forms/i-130.pdf" | |
| # PDF document password. Leave empty for unprotected documents. | |
| Password = "" | |
| # Destination PDF file name | |
| DestinationFile = "result.pdf" | |
| # Runs processing asynchronously. Returns Use JobId that you may use with /job/check to check state of the processing (possible states: working, failed, aborted and success). Must be one of: true, false. | |
| Async = "False" | |
| # Values to fill out pdf fields with built-in pdf form filler. | |
| # To fill fields in PDF form, use the following format page;fieldName;value for example: 0;editbox1;text is here. To fill checkbox, use true, for example: 0;checkbox1;true. To separate multiple objects, use | separator. To get the list of all fillable fields in PDF form please use /pdf/info/fields endpoint. | |
| # response = { } | |
| FieldsStrings = "" | |
| # spouse | |
| if response["is spouse?"] == "yes": | |
| FieldsStrings += "0;form1[0].#subform[0].Pt1Line1_Spouse[0];True|" | |
| FieldsStrings += "0;form1[0].#subform[0].Pt1Line3_No[0];True|" | |
| # brother/siste | |
| if response["is brother/sister?"] == "yes": | |
| FieldsStrings += "0;form1[0].#subform[0].Pt1Line1_Siblings[0];True|" | |
| if response["sibling related through adoption?"] == "yes": | |
| FieldsStrings += "0;form1[0].#subform[0].Pt1Line3_Yes[0];True|" | |
| # parent | |
| if response["is parent?"] == "yes": | |
| FieldsStrings += "0;form1[0].#subform[0].Pt1Line1_Parent[0];True|" | |
| # child | |
| if response["is child?"] == "yes": | |
| FieldsStrings += "0;form1[0].#subform[0].Pt1Line1_Child[0];True|" | |
| # stepchild/stepparent | |
| if response["Stepchild/Stepparent?"] == "yes": | |
| FieldsStrings += "0;form1[0].#subform[0].Pt1Line2_Stepchild[0];True|" | |
| else: | |
| # child/parent status | |
| if response["Child was born to parents who were married?"] == "yes": | |
| FieldsStrings += "0;form1[0].#subform[0].Pt1Line2_InWedlock[0];True|" | |
| if response["Child was born to parents who were not married?"] == "yes": | |
| FieldsStrings += "0;form1[0].#subform[0].Pt1Line2_OutOfWedlock[0];True|" | |
| # adopted | |
| if response["Child was adopted?"] == "yes": | |
| FieldsStrings += "0;form1[0].#subform[0].Pt1Line2_AdoptedChild[0];True|" | |
| # naming | |
| FieldsStrings += "0;form1[0].#subform[0].Pt2Line4a_FamilyName[0];" + response[ | |
| "family name"] + "|" | |
| FieldsStrings += "0;form1[0].#subform[0].Pt2Line4b_GivenName[0];" + response[ | |
| "given name"] + "|" | |
| FieldsStrings += "0;form1[0].#subform[0].Pt2Line4c_MiddleName[0];" + response[ | |
| "middle name"] + "|" | |
| # brother/sister adoption? | |
| if response["sibling related through adoption?"] == "yes": | |
| FieldsStrings += "0;form1[0].#subform[0].Pt1Line3_Yes[0];True|" | |
| else: | |
| FieldsStrings += "0;form1[0].#subform[0].Pt1Line4_No[0];True|" | |
| # resident status | |
| if response["permanent resident status through adoption?"] == "yes": | |
| FieldsStrings += "0;form1[0].#subform[0].Pt1Line4_Yes[0];True|" | |
| else: | |
| FieldsStrings += "0;form1[0].#subform[0].Pt1Line3_No[0];True|" | |
| # [age 1 ended without number] | |
| # geneder | |
| if response["sex"] == "male": | |
| FieldsStrings += "1;form1[0].#subform[1].Pt2Line9_Male[0];True|" | |
| if response["sex"] == "female": | |
| FieldsStrings += "1;form1[0].#subform[1].Pt2Line9_Female[0];True|" | |
| # dob | |
| FieldsStrings += "1;form1[0].#subform[1].Pt2Line8_DateofBirth[0];" + response[ | |
| "date of birth"] + "|" | |
| # country of birth | |
| FieldsStrings += "1;form1[0].#subform[1].Pt2Line7_CountryofBirth[0];" + response[ | |
| "country of birth"] + "|" | |
| # city of birth | |
| FieldsStrings += "1;form1[0].#subform[1].Pt2Line6_CityTownOfBirth[0];" + response[ | |
| "city of birth"] + "|" | |
| # street number | |
| FieldsStrings += "1;form1[0].#subform[1].Pt2Line10_StreetNumberName[0];" + response[ | |
| "street number and name"] + "|" | |
| # residency type | |
| if response["residency type"] == "apt.": | |
| FieldsStrings += "1;form1[0].#subform[1].Pt2Line10_Unit[0];True|" | |
| if response["residency type"] == "ste.": | |
| FieldsStrings += "1;form1[0].#subform[1].Pt2Line10_Unit[0];True|" | |
| if response["residency type"] == "flr.": | |
| FieldsStrings += "1;form1[0].#subform[1].Pt2Line10_Unit[0];True|" | |
| # in care person name | |
| FieldsStrings += "1;form1[0].#subform[1].Pt2Line10_InCareofName[0];" + response[ | |
| "in care person name"] + "|" | |
| # city/town | |
| FieldsStrings += "1;form1[0].#subform[1].Pt2Line10_CityOrTown[0];" + response[ | |
| "city/town"] + "|" | |
| # province | |
| FieldsStrings += "1;form1[0].#subform[1].Pt2Line10_Province[0];" + response[ | |
| "province"] + "|" | |
| # postal code | |
| FieldsStrings += "1;form1[0].#subform[1].Pt2Line10_PostalCode[0];" + response[ | |
| "postal code"] + "|" | |
| # zip code | |
| FieldsStrings += "1;form1[0].#subform[1].Pt2Line10_ZipCode[0];" + response[ | |
| "zip code"] + "|" | |
| # state | |
| FieldsStrings += "1;form1[0].#subform[1].Pt2Line10_State[0];" + response[ | |
| "state"] + "|" | |
| # country | |
| FieldsStrings += "1;form1[0].#subform[1].Pt2Line10_Country[0];" + response[ | |
| "country"] + "|" | |
| # date from | |
| FieldsStrings += "1;form1[0].#subform[1].Pt2Line13a_DateFrom[0];" + response[ | |
| "date from"] + "|" | |
| # no of time married | |
| FieldsStrings += "1;form1[0].#subform[1].Pt2Line16_NumberofMarriages[0];" + response["no of time married"] + "|" | |
| # martial stauts | |
| if response["martial status"] == "married": | |
| FieldsStrings += "1;form1[0].#subform[1].Pt2Line17_Married[0];True|" | |
| # page 3 | |
| # date of marriage | |
| FieldsStrings += "2;form1[0].#subform[2].Pt2Line18_DateOfMarriage[0]" + response["date of marriage"] + "|" | |
| # place of marriage | |
| FieldsStrings += "2;form1[0].#subform[2].Pt2Line19a_CityTown[0]" + response["city of marriage"] + "|" | |
| FieldsStrings += "2;form1[0].#subform[2].Pt2Line19b_State[0]" + response["state of marriage"] + "|" | |
| FieldsStrings += "2;form1[0].#subform[2].Pt2Line19c_Province[0]" + response["province of marriage"] + "|" | |
| FieldsStrings += "2;form1[0].#subform[2].Pt2Line19d_Country[0]" + response["country of marriage"] + "|" | |
| # resident type | |
| if response["us citizen?"] == "yes": | |
| FieldsStrings += "2;form1[0].#subform[2].Pt2Line36_USCitizen[0];True|" | |
| else: | |
| FieldsStrings += "2;form1[0].#subform[2].Pt2Line36_LPR[0];True|" | |
| def main(args=None): | |
| fillPDFForm(SourceFileUrl, DestinationFile) | |
| def fillPDFForm(uploadedFileUrl, destinationFile): | |
| """Converts HTML to PDF using PDF.co Web API""" | |
| parameters = {} | |
| parameters["name"] = os.path.basename(destinationFile) | |
| parameters["url"] = uploadedFileUrl | |
| parameters["fieldsString"] = FieldsStrings | |
| parameters["async"] = Async | |
| # Prepare URL for 'Fill PDF' API request | |
| url = "{}/pdf/edit/add".format(BASE_URL) | |
| # Execute request and get response as JSON | |
| response = requests.post(url, data=parameters, headers={"x-api-key": API_KEY}) | |
| if (response.status_code == 200): | |
| json = response.json() | |
| if json["error"] == False: | |
| # Get URL of result file | |
| resultFileUrl = json["url"] | |
| # Download result file | |
| r = requests.get(resultFileUrl, stream=True) | |
| if (r.status_code == 200): | |
| with open(destinationFile, 'wb') as file: | |
| for chunk in r: | |
| file.write(chunk) | |
| print(f"Result file saved as \"{destinationFile}\" file.") | |
| else: | |
| print(f"Request error: {response.status_code} {response.reason}") | |
| else: | |
| # Show service reported error | |
| print(json["message"]) | |
| else: | |
| print(f"Request error: {response.status_code} {response.reason}") | |
| if __name__ == '__main__': | |
| main() | |
| print("done") | |
| def end_interview(chat_history): | |
| # Open the file in read mode | |
| chatburh = convert_tuples_to_list(chat_history) | |
| # print(completion.choices[0].message.content.strip()) | |
| print(chatburh) | |
| gpt_result = process_text(chatburh, file_contents) | |
| print(gpt_result) | |
| # fill_the_form(gpt_result) | |
| return chat_history | |
| with gr.Blocks() as app2: | |
| chatbot = gr.Chatbot() | |
| msg = gr.Textbox() | |
| msg.submit(run_text_prompt, [msg, chatbot], [msg, chatbot]) | |
| with gr.Row(): | |
| audio = gr.Audio(source="microphone", type="filepath") | |
| fn = run_audio_prompt, | |
| inputs = [audio, chatbot], | |
| outputs = [audio, chatbot] | |
| # fn = run_audio_prompt, | |
| # inputs = [audio, chatbot], | |
| # outputs = [audio, chatbot] | |
| audio.change(run_audio_prompt, [audio, chatbot], [audio, chatbot]) | |
| # send_audio_button = gr.Button("Send Audio", interactive=True) | |
| # send_audio_button.click(run_audio_prompt, [audio, chatbot], [audio, chatbot]) | |
| send_audio_button = gr.Button("End Interview", interactive=True) | |
| send_audio_button.click(end_interview, [chatbot], [chatbot]) | |
| with gr.Blocks() as app1: | |
| gr.Markdown("""<h1><center>Instructions for the interview</center></h1>""") | |
| gr.Markdown("""<h2>Thank you for taking your time for interview.</h2>""") | |
| gr.Markdown("""* First point | |
| * Second point | |
| * Third point""") | |
| gr.Markdown("""<h2>Please follow.</h2>""") | |
| gr.Markdown("""> Please press "End Interview" button once Interview is finished. """) | |
| gr.Markdown("""> This is all one single quoted | |
| paragraph even though it is spread | |
| over several.""") | |
| gr.Markdown("""> This is all one single quoted | |
| paragraph even though i.""") | |
| gr.Markdown("""> This is all one single quoted | |
| paragraph.""") | |
| demo = gr.TabbedInterface([app1, app2], ["Instructions", "Interview"]) | |
| demo.launch(share=False, | |
| debug=False) | |