Nechba commited on
Commit
b108c0c
·
verified ·
1 Parent(s): 73e3c61

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -152
app.py CHANGED
@@ -1,152 +1,152 @@
1
- from fastapi import FastAPI, File, UploadFile, HTTPException
2
- import speech_recognition as sr
3
- from io import BytesIO
4
- import os
5
- from pydantic import BaseModel
6
- import google.generativeai as genai
7
- import openai
8
-
9
- app = FastAPI()
10
-
11
- def audio_to_text_intern(audio_data, language='fr-FR'):
12
- with sr.AudioFile(audio_data) as source:
13
- recognizer = sr.Recognizer()
14
- audio = recognizer.record(source)
15
- try:
16
- text = recognizer.recognize_google(audio, language=language)
17
- return text
18
- except sr.UnknownValueError:
19
- return "Unable to understand the audio"
20
- except sr.RequestError as e:
21
- return f"Service error: {e}"
22
-
23
- def generate_job_description_gemini(input_text, key):
24
- # Set up the model
25
- import google.generativeai as genai
26
- genai.configure(api_key=key)
27
- prompt = f"""
28
- Transforme le texte ci-dessous, qui est une transcription d'un enregistrement audio où un recruteur décrit un projet, en une description d'offre d'emploi complète et structurée. La description doit suivre le format ci-dessous :
29
-
30
- 1. Description de l'activité de l'entreprise :
31
- 2. Description du contexte du projet :
32
- 3. Objectifs et livrables identifiés :
33
- 4. Compétences fonctionnelles et techniques :
34
-
35
- Texte :
36
- "{input_text}"
37
-
38
- La description d'offre d'emploi doit être détaillée et couvrir les points suivants :
39
- - L'activité de l'entreprise et ses domaines d'expertise.
40
- - Le contexte du projet et sa pertinence pour l'entreprise.
41
- - Les objectifs spécifiques du projet et les livrables attendus.
42
- - Les compétences techniques et fonctionnelles requises pour le poste, ainsi que les conditions de travail (par exemple, la possibilité de travail en remote et la rémunération)."""
43
-
44
-
45
- generation_config = {
46
- "temperature": 1,
47
- "top_p": 0.95,
48
- "max_output_tokens": 5000000,
49
- }
50
- model = genai.GenerativeModel(model_name="gemini-1.0-pro-latest",
51
- generation_config=generation_config)
52
- response = model.generate_content(prompt)
53
- return response.text
54
-
55
- def generate_job_description_gpt(input_text, key):
56
- import openai
57
- openai.api_key = key
58
- prompt = f"""
59
- Transforme le texte ci-dessous, qui est une transcription d'un enregistrement audio où un recruteur décrit un projet, en une description d'offre d'emploi complète et structurée. La description doit suivre le format ci-dessous :
60
-
61
- 1. Description de l'activité de l'entreprise :
62
- 2. Description du contexte du projet :
63
- 3. Objectifs et livrables identifiés :
64
- 4. Compétences fonctionnelles et techniques :
65
-
66
- Texte :
67
- "{input_text}"
68
-
69
- La description d'offre d'emploi doit être détaillée et couvrir les points suivants :
70
- - L'activité de l'entreprise et ses domaines d'expertise.
71
- - Le contexte du projet et sa pertinence pour l'entreprise.
72
- - Les objectifs spécifiques du projet et les livrables attendus.
73
- - Les compétences techniques et fonctionnelles requises pour le poste, ainsi que les conditions de travail (par exemple, la possibilité de travail en remote et la rémunération)."""
74
-
75
-
76
- generation_config = {
77
- "temperature": 1,
78
- "top_p": 0.95,
79
- "max_output_tokens": 5000000,
80
- }
81
- response = openai.ChatCompletion.create(
82
- model="gpt-4o-mini",
83
- messages=[
84
- # {"role": "system", "content": "Vous êtes un createur de contenu qui génère des fausses réponses pour une question."},
85
- {"role": "user", "content": prompt}
86
- ],
87
- **generation_config
88
- )
89
-
90
- answers_text = response.choices[0].message['content']
91
- return answers_text
92
-
93
-
94
- @app.post("/audio-to-text/")
95
- async def audio_to_text_endpoint(file: UploadFile, language: str = 'fr-FR'):
96
- """
97
- Endpoint to upload an audio file and convert its content to text.
98
-
99
- Args:
100
- file (UploadFile): The audio file uploaded by the client. The file should be in .wav format.
101
- language (str, optional): The language code to be used in speech-to-text conversion. Defaults to 'fr-FR' for French.
102
-
103
- Returns:
104
- dict: A dictionary containing the converted text under the key 'text'.
105
-
106
- Raises:
107
- HTTPException: An error 500 if there is any issue during the file processing.
108
- """
109
- try:
110
- # Read the audio file provided by the client
111
- audio_data = await file.read()
112
-
113
- # Convert byte data to a BytesIO object for processing
114
- audio_stream = BytesIO(audio_data)
115
-
116
- # Convert the audio stream to text using a speech-to-text conversion function
117
- text = audio_to_text_intern(audio_stream, language)
118
-
119
- # Return the converted text as part of the response
120
- return {"text": text}
121
- except Exception as e:
122
- # Raise an HTTP 500 error if any exceptions occur
123
- raise HTTPException(status_code=500, detail=f"An error occurred while processing the file: {e}")
124
-
125
- @app.post("/audio-to-offer-endpoint/")
126
- async def audio_to_offer_endpoint(file: UploadFile, language: str, api_key: str):
127
- """
128
- Endpoint to convert uploaded audio content to a job offer text.
129
-
130
- Parameters:
131
- - file (UploadFile): The audio file uploaded by the client. The file should be in .wav format.
132
- - language (str): Language code to guide the speech recognition process. Default is French ('fr-FR').
133
- - api_key (str, optional): API key for accessing extended features or third-party services used in generating the job offer.
134
-
135
- Returns:
136
- - A JSON object with a key 'offer' containing the generated job description text based on the audio content.
137
-
138
- Raises:
139
- - HTTPException: If an error occurs during the processing of the audio or the generation of the job offer.
140
- """
141
- print(language)
142
- print(api_key)
143
- try:
144
- text_response = await audio_to_text_endpoint(file, language)
145
- text = text_response["text"]
146
- offer = generate_job_description_gemini(text, api_key)
147
- return {"text": offer}
148
- except Exception as e:
149
- raise HTTPException(status_code=500, detail=f"Error generating job offer: {e}")
150
- if __name__ == "__main__":
151
- import uvicorn
152
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
1
+ from fastapi import FastAPI, File, UploadFile, HTTPException
2
+ import speech_recognition as sr
3
+ from io import BytesIO
4
+ import os
5
+ from pydantic import BaseModel
6
+ import google.generativeai as genai
7
+ import openai
8
+
9
+ app = FastAPI()
10
+
11
+ def audio_to_text_intern(audio_data, language='fr-FR'):
12
+ with sr.AudioFile(audio_data) as source:
13
+ recognizer = sr.Recognizer()
14
+ audio = recognizer.record(source)
15
+ try:
16
+ text = recognizer.recognize_google(audio, language=language)
17
+ return text
18
+ except sr.UnknownValueError:
19
+ return "Unable to understand the audio"
20
+ except sr.RequestError as e:
21
+ return f"Service error: {e}"
22
+
23
+ def generate_job_description_gemini(input_text, key):
24
+ # Set up the model
25
+ import google.generativeai as genai
26
+ genai.configure(api_key=key)
27
+ prompt = f"""
28
+ Transforme le texte ci-dessous, qui est une transcription d'un enregistrement audio où un recruteur décrit un projet, en une description d'offre d'emploi complète et structurée. La description doit suivre le format ci-dessous :
29
+
30
+ 1. Description de l'activité de l'entreprise :
31
+ 2. Description du contexte du projet :
32
+ 3. Objectifs et livrables identifiés :
33
+ 4. Compétences fonctionnelles et techniques :
34
+
35
+ Texte :
36
+ "{input_text}"
37
+
38
+ La description d'offre d'emploi doit être détaillée et couvrir les points suivants :
39
+ - L'activité de l'entreprise et ses domaines d'expertise.
40
+ - Le contexte du projet et sa pertinence pour l'entreprise.
41
+ - Les objectifs spécifiques du projet et les livrables attendus.
42
+ - Les compétences techniques et fonctionnelles requises pour le poste, ainsi que les conditions de travail (par exemple, la possibilité de travail en remote et la rémunération)."""
43
+
44
+
45
+ generation_config = {
46
+ "temperature": 1,
47
+ "top_p": 0.95,
48
+ "max_output_tokens": 5000000,
49
+ }
50
+ model = genai.GenerativeModel(model_name="gemini-1.0-pro-latest",
51
+ generation_config=generation_config)
52
+ response = model.generate_content(prompt)
53
+ return response.text
54
+
55
+ def generate_job_description_gpt(input_text, key):
56
+ import openai
57
+ openai.api_key = key
58
+ prompt = f"""
59
+ Transforme le texte ci-dessous, qui est une transcription d'un enregistrement audio où un recruteur décrit un projet, en une description d'offre d'emploi complète et structurée. La description doit suivre le format ci-dessous :
60
+
61
+ 1. Description de l'activité de l'entreprise :
62
+ 2. Description du contexte du projet :
63
+ 3. Objectifs et livrables identifiés :
64
+ 4. Compétences fonctionnelles et techniques :
65
+
66
+ Texte :
67
+ "{input_text}"
68
+
69
+ La description d'offre d'emploi doit être détaillée et couvrir les points suivants :
70
+ - L'activité de l'entreprise et ses domaines d'expertise.
71
+ - Le contexte du projet et sa pertinence pour l'entreprise.
72
+ - Les objectifs spécifiques du projet et les livrables attendus.
73
+ - Les compétences techniques et fonctionnelles requises pour le poste, ainsi que les conditions de travail (par exemple, la possibilité de travail en remote et la rémunération)."""
74
+
75
+
76
+ generation_config = {
77
+ "temperature": 1,
78
+ "top_p": 0.95,
79
+ "max_output_tokens": 5000000,
80
+ }
81
+ response = openai.ChatCompletion.create(
82
+ model="gpt-4o-mini",
83
+ messages=[
84
+ # {"role": "system", "content": "Vous êtes un createur de contenu qui génère des fausses réponses pour une question."},
85
+ {"role": "user", "content": prompt}
86
+ ],
87
+ **generation_config
88
+ )
89
+
90
+ answers_text = response.choices[0].message['content']
91
+ return answers_text
92
+
93
+
94
+ @app.post("/audio-to-text/")
95
+ async def audio_to_text_endpoint(file: UploadFile, language: str = 'fr-FR'):
96
+ """
97
+ Endpoint to upload an audio file and convert its content to text.
98
+
99
+ Args:
100
+ file (UploadFile): The audio file uploaded by the client. The file should be in .wav format.
101
+ language (str, optional): The language code to be used in speech-to-text conversion. Defaults to 'fr-FR' for French.
102
+
103
+ Returns:
104
+ dict: A dictionary containing the converted text under the key 'text'.
105
+
106
+ Raises:
107
+ HTTPException: An error 500 if there is any issue during the file processing.
108
+ """
109
+ try:
110
+ # Read the audio file provided by the client
111
+ audio_data = await file.read()
112
+
113
+ # Convert byte data to a BytesIO object for processing
114
+ audio_stream = BytesIO(audio_data)
115
+
116
+ # Convert the audio stream to text using a speech-to-text conversion function
117
+ text = audio_to_text_intern(audio_stream, language)
118
+
119
+ # Return the converted text as part of the response
120
+ return {"text": text}
121
+ except Exception as e:
122
+ # Raise an HTTP 500 error if any exceptions occur
123
+ raise HTTPException(status_code=500, detail=f"An error occurred while processing the file: {e}")
124
+
125
+ @app.post("/audio-to-offer-endpoint/")
126
+ async def audio_to_offer_endpoint(file: UploadFile, language: str, api_key: str):
127
+ """
128
+ Endpoint to convert uploaded audio content to a job offer text.
129
+
130
+ Parameters:
131
+ - file (UploadFile): The audio file uploaded by the client. The file should be in .wav format.
132
+ - language (str): Language code to guide the speech recognition process. Default is French ('fr-FR').
133
+ - api_key (str, optional): API key for accessing extended features or third-party services used in generating the job offer.
134
+
135
+ Returns:
136
+ - A JSON object with a key 'offer' containing the generated job description text based on the audio content.
137
+
138
+ Raises:
139
+ - HTTPException: If an error occurs during the processing of the audio or the generation of the job offer.
140
+ """
141
+ print(language)
142
+ print(api_key)
143
+ try:
144
+ text_response = await audio_to_text_endpoint(file, language)
145
+ text = text_response["text"]
146
+ offer = generate_job_description_gemini(text, api_key)
147
+ return {"text": offer}
148
+ except Exception as e:
149
+ raise HTTPException(status_code=500, detail=f"Error generating job offer: {e}")
150
+ # if __name__ == "__main__":
151
+ # import uvicorn
152
+ # uvicorn.run(app, host="0.0.0.0", port=8000)