Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,30 +5,46 @@ from huggingface_hub import InferenceClient
|
|
| 5 |
from fpdf import FPDF
|
| 6 |
import uuid
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
def generate_pdf_from_chat(chat_history):
|
| 9 |
-
if not chat_history or not isinstance(chat_history, list)
|
| 10 |
return None
|
| 11 |
|
| 12 |
-
# Extract the last assistant message (i.e. the bot's response)
|
| 13 |
try:
|
| 14 |
last_response = chat_history[-1][1]
|
| 15 |
except (IndexError, TypeError):
|
| 16 |
last_response = "No response available."
|
| 17 |
|
| 18 |
-
|
| 19 |
-
file_name = f"/tmp/chat_response_{uuid.uuid4().hex}.pdf"
|
| 20 |
|
| 21 |
-
# Create PDF
|
| 22 |
pdf = FPDF()
|
| 23 |
pdf.add_page()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
pdf.set_auto_page_break(auto=True, margin=15)
|
| 25 |
-
pdf.set_font("Arial", size=12)
|
| 26 |
|
|
|
|
| 27 |
for line in last_response.split("\n"):
|
| 28 |
pdf.multi_cell(0, 10, line)
|
| 29 |
|
| 30 |
-
pdf.output(
|
| 31 |
-
return
|
| 32 |
|
| 33 |
#_______________________________________________________________________
|
| 34 |
|
|
|
|
| 5 |
from fpdf import FPDF
|
| 6 |
import uuid
|
| 7 |
|
| 8 |
+
from urllib.request import urlretrieve
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
FONT_DIR = "/tmp/fonts"
|
| 12 |
+
FONT_PATH = os.path.join(FONT_DIR, "DejaVuSans.ttf")
|
| 13 |
+
|
| 14 |
+
# Create font dir and download font only if needed
|
| 15 |
+
os.makedirs(FONT_DIR, exist_ok=True)
|
| 16 |
+
if not os.path.exists(FONT_PATH):
|
| 17 |
+
urlretrieve(
|
| 18 |
+
"https://github.com/dejavu-fonts/dejavu-fonts/raw/master/ttf/DejaVuSans.ttf",
|
| 19 |
+
FONT_PATH
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
def generate_pdf_from_chat(chat_history):
|
| 23 |
+
if not chat_history or not isinstance(chat_history, list):
|
| 24 |
return None
|
| 25 |
|
|
|
|
| 26 |
try:
|
| 27 |
last_response = chat_history[-1][1]
|
| 28 |
except (IndexError, TypeError):
|
| 29 |
last_response = "No response available."
|
| 30 |
|
| 31 |
+
file_path = f"/tmp/chat_response_{uuid.uuid4().hex}.pdf"
|
|
|
|
| 32 |
|
| 33 |
+
# Create PDF with Unicode support
|
| 34 |
pdf = FPDF()
|
| 35 |
pdf.add_page()
|
| 36 |
+
|
| 37 |
+
# Register Unicode font
|
| 38 |
+
pdf.add_font("DejaVu", "", FONT_PATH, uni=True)
|
| 39 |
+
pdf.set_font("DejaVu", size=12)
|
| 40 |
pdf.set_auto_page_break(auto=True, margin=15)
|
|
|
|
| 41 |
|
| 42 |
+
# Add the text safely
|
| 43 |
for line in last_response.split("\n"):
|
| 44 |
pdf.multi_cell(0, 10, line)
|
| 45 |
|
| 46 |
+
pdf.output(file_path)
|
| 47 |
+
return file_path
|
| 48 |
|
| 49 |
#_______________________________________________________________________
|
| 50 |
|