ImHadis commited on
Commit
09d74f6
·
verified ·
1 Parent(s): a08c503

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -21
app.py CHANGED
@@ -4,40 +4,41 @@ import requests, json
4
  from transformers import pipeline
5
  import gradio as gr
6
 
 
7
  # Access the Hugging Face API key and endpoint URL
8
  hf_api_key = os.getenv('HF_API_KEY')
9
- ENDPOINT_URL = os.getenv('HF_API_SUMMARY_BASE')
 
10
 
11
  #Summarization endpoint
12
- def get_completion(inputs, parameters=None, ENDPOINT_URL=ENDPOINT_URL):
13
  headers = {
14
- "Authorization": f"Bearer {hf_api_key}",
15
- "Content-Type": "application/json"
 
 
 
16
  }
17
- data = { "inputs": inputs }
18
  if parameters is not None:
19
  data.update({"parameters": parameters})
20
 
21
  try:
22
- response = requests.request("POST",
23
- ENDPOINT_URL, headers=headers,
24
- data=json.dumps(data)
25
- )
26
- if response.status_code == 200:
27
- return json.loads(response.content.decode("utf-8"))
28
- else:
29
- print(f"Error: Received status code {response.status_code}")
30
- return {"error": f"Bad response: {response.status_code}"}
31
  except requests.exceptions.RequestException as e:
32
  print(f"Request failed: {e}")
33
- return {"error": "Request failed"}
34
- except json.JSONDecodeError as e:
35
- print(f"JSON decoding failed: {e}")
36
- return {"error": "Invalid JSON response"}
37
 
38
- def summarize(input):
39
- output = get_completion(input)
40
- return output[0]['summary_text']
 
 
 
 
 
 
41
 
42
  demo = gr.Interface(fn=summarize, inputs="text", outputs="text")
43
  demo.launch()
 
4
  from transformers import pipeline
5
  import gradio as gr
6
 
7
+ load_dotenv()
8
  # Access the Hugging Face API key and endpoint URL
9
  hf_api_key = os.getenv('HF_API_KEY')
10
+ MODEL_NAME = "sshleifer/distilbart-cnn-12-6"
11
+ ENDPOINT_URL = f"https://api-inference.huggingface.co/models/{MODEL_NAME}"
12
 
13
  #Summarization endpoint
14
+ def get_completion(inputs, parameters=None):
15
  headers = {
16
+ "Authorization": f"Bearer {hf_api_key}",
17
+ "Content-Type": "application/json"
18
+ }
19
+ data = {
20
+ "inputs": inputs
21
  }
 
22
  if parameters is not None:
23
  data.update({"parameters": parameters})
24
 
25
  try:
26
+ response = requests.post(ENDPOINT_URL, headers=headers, json=data)
27
+ response.raise_for_status()
28
+ return response.json()
 
 
 
 
 
 
29
  except requests.exceptions.RequestException as e:
30
  print(f"Request failed: {e}")
31
+ return {"error": f"Request failed: {str(e)}"}
 
 
 
32
 
33
+ def summarize(input_text):
34
+ try:
35
+ output = get_completion(input_text)
36
+ if isinstance(output, list) and len(output) > 0 and 'summary_text' in output[0]:
37
+ return output[0]['summary_text']
38
+ else:
39
+ return f"Unexpected response format: {output}"
40
+ except Exception as e:
41
+ return f"An error occurred: {str(e)}"
42
 
43
  demo = gr.Interface(fn=summarize, inputs="text", outputs="text")
44
  demo.launch()