ImHadis commited on
Commit
d6d41eb
·
verified ·
1 Parent(s): 7fa60e7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -36
app.py CHANGED
@@ -1,57 +1,45 @@
1
  import os
2
  from dotenv import load_dotenv
3
  import requests
 
4
  import gradio as gr
5
- import logging
6
-
7
- # Set up logging
8
- logging.basicConfig(level=logging.INFO)
9
- logger = logging.getLogger(__name__)
10
 
11
  # Load environment variables
12
  load_dotenv()
13
 
14
- # Access the Hugging Face API key
15
  hf_api_key = os.getenv('HF_API_KEY')
16
-
17
- # Check if the API key is available
18
- if not hf_api_key:
19
- logger.error("HF_API_KEY is not set in the environment variables.")
20
- raise ValueError("HF_API_KEY is missing. Please set it in your environment or .env file.")
21
-
22
- # Log a part of the API key for verification (be careful not to log the entire key)
23
- logger.info(f"Using API key starting with: {hf_api_key[:4]}{'*' * (len(hf_api_key) - 4)}")
24
-
25
- # Set up the API endpoint
26
- API_URL = "https://api-inference.huggingface.co/models/sshleifer/distilbart-cnn-12-6"
27
- headers = {"Authorization": f"Bearer {hf_api_key}"}
28
-
29
- def query(payload):
30
- response = requests.post(API_URL, headers=headers, json=payload)
31
- if response.status_code != 200:
32
- logger.error(f"API request failed with status code {response.status_code}")
33
- logger.error(f"Response content: {response.text}")
34
- return response.json()
 
 
35
 
36
  def summarize(input_text):
37
  try:
38
- output = query({
39
- "inputs": input_text,
40
- "parameters": {"max_length": 130, "min_length": 30}
41
- })
42
-
43
  if isinstance(output, list) and len(output) > 0 and 'summary_text' in output[0]:
44
  return output[0]['summary_text']
45
- elif isinstance(output, dict) and 'error' in output:
46
- logger.error(f"API Error: {output['error']}")
47
- return f"API Error: {output['error']}"
48
  else:
49
- logger.error(f"Unexpected response format: {output}")
50
  return f"Unexpected response format: {output}"
51
  except Exception as e:
52
- logger.exception("An error occurred during summarization")
53
  return f"An error occurred: {str(e)}"
54
 
55
- # Create and launch the Gradio interface
56
  demo = gr.Interface(fn=summarize, inputs="text", outputs="text")
57
  demo.launch()
 
1
  import os
2
  from dotenv import load_dotenv
3
  import requests
4
+ import json
5
  import gradio as gr
 
 
 
 
 
6
 
7
  # Load environment variables
8
  load_dotenv()
9
 
10
+ # Access the Hugging Face API key and endpoint URL
11
  hf_api_key = os.getenv('HF_API_KEY')
12
+ MODEL_NAME = "sshleifer/distilbart-cnn-12-6"
13
+ ENDPOINT_URL = f"https://api-inference.huggingface.co/models/{MODEL_NAME}"
14
+
15
+ def get_completion(inputs, parameters=None):
16
+ headers = {
17
+ "Authorization": f"Bearer {hf_api_key}",
18
+ "Content-Type": "application/json"
19
+ }
20
+ data = {
21
+ "inputs": inputs
22
+ }
23
+ if parameters is not None:
24
+ data.update({"parameters": parameters})
25
+
26
+ try:
27
+ response = requests.post(ENDPOINT_URL, headers=headers, json=data)
28
+ response.raise_for_status()
29
+ return response.json()
30
+ except requests.exceptions.RequestException as e:
31
+ print(f"Request failed: {e}")
32
+ return {"error": f"Request failed: {str(e)}"}
33
 
34
  def summarize(input_text):
35
  try:
36
+ output = get_completion(input_text)
 
 
 
 
37
  if isinstance(output, list) and len(output) > 0 and 'summary_text' in output[0]:
38
  return output[0]['summary_text']
 
 
 
39
  else:
 
40
  return f"Unexpected response format: {output}"
41
  except Exception as e:
 
42
  return f"An error occurred: {str(e)}"
43
 
 
44
  demo = gr.Interface(fn=summarize, inputs="text", outputs="text")
45
  demo.launch()