Sefat33 commited on
Commit
6bf08a0
·
verified ·
1 Parent(s): 41073c3

Update utils.py

Browse files
Files changed (1) hide show
  1. utils.py +15 -16
utils.py CHANGED
@@ -1,21 +1,24 @@
1
  import os
2
  import requests
 
3
  from transformers import pipeline
4
 
5
- # Set Hugging Face cache directory to avoid /.cache permission error
6
- os.environ["HF_HOME"] = "./hf_cache"
7
- os.makedirs("./hf_cache", exist_ok=True)
 
8
 
9
- # Load a text generation model like GPT-2 safely
10
  try:
11
  generator = pipeline(
12
  "text-generation",
13
  model="gpt2",
14
- cache_dir="./hf_cache"
 
15
  )
16
  except Exception as e:
17
  generator = None
18
- print("⚠️ Failed to load GPT-2 model:", e)
19
 
20
 
21
  def generate_description(country_name):
@@ -23,22 +26,19 @@ def generate_description(country_name):
23
  Generate a simple English description about a country using GPT-2.
24
  """
25
  if not generator:
26
- return "⚠️ Model is not available. Please check the server logs."
27
 
28
  try:
29
  prompt = f"Tell me about {country_name}."
30
  result = generator(prompt, max_length=100, do_sample=True)
31
- if result and isinstance(result, list):
32
- return result[0]["generated_text"].strip()
33
- else:
34
- return "⚠️ Failed to generate text."
35
  except Exception as e:
36
- return f"⚠️ Error generating description: {str(e)}"
37
 
38
 
39
  def get_country_info(country_name):
40
  """
41
- Fetch country data from restcountries.com API.
42
  """
43
  try:
44
  url = f"https://restcountries.com/v3.1/name/{country_name}"
@@ -53,9 +53,8 @@ def get_country_info(country_name):
53
  "Languages": ", ".join(data.get("languages", {}).values())
54
  }
55
  return info
56
-
57
  except Exception as e:
58
- return {"error": f"⚠️ Could not retrieve data for {country_name}."}
59
 
60
 
61
  def translate_to_bangla(text):
@@ -74,5 +73,5 @@ def translate_to_bangla(text):
74
  }
75
  )
76
  return response.json().get("translatedText", "⚠️ Translation failed.")
77
- except Exception as e:
78
  return "⚠️ Translation API error."
 
1
  import os
2
  import requests
3
+ import tempfile
4
  from transformers import pipeline
5
 
6
+ # Use a safe writable temporary directory
7
+ cache_dir = os.path.join(tempfile.gettempdir(), "hf_cache")
8
+ os.environ["HF_HOME"] = cache_dir
9
+ os.makedirs(cache_dir, exist_ok=True)
10
 
11
+ # Load GPT-2 safely into tmp directory
12
  try:
13
  generator = pipeline(
14
  "text-generation",
15
  model="gpt2",
16
+ cache_dir=cache_dir,
17
+ local_files_only=False
18
  )
19
  except Exception as e:
20
  generator = None
21
+ print("⚠️ GPT-2 model loading failed:", e)
22
 
23
 
24
  def generate_description(country_name):
 
26
  Generate a simple English description about a country using GPT-2.
27
  """
28
  if not generator:
29
+ return "⚠️ Model unavailable."
30
 
31
  try:
32
  prompt = f"Tell me about {country_name}."
33
  result = generator(prompt, max_length=100, do_sample=True)
34
+ return result[0]["generated_text"].strip()
 
 
 
35
  except Exception as e:
36
+ return f"⚠️ Error: {str(e)}"
37
 
38
 
39
  def get_country_info(country_name):
40
  """
41
+ Get basic country info using REST Countries API.
42
  """
43
  try:
44
  url = f"https://restcountries.com/v3.1/name/{country_name}"
 
53
  "Languages": ", ".join(data.get("languages", {}).values())
54
  }
55
  return info
 
56
  except Exception as e:
57
+ return {"error": f"⚠️ Failed to retrieve country data."}
58
 
59
 
60
  def translate_to_bangla(text):
 
73
  }
74
  )
75
  return response.json().get("translatedText", "⚠️ Translation failed.")
76
+ except Exception:
77
  return "⚠️ Translation API error."