Files changed (1) hide show
  1. app.py +94 -54
app.py CHANGED
@@ -1,64 +1,104 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
 
 
 
 
 
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
  stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
 
 
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
+ import os
4
+ import requests
5
+ import json
6
+ import pytesseract
7
+ from PIL import Image
8
+ import PyPDF2
9
+ from io import BytesIO
10
+ import docx
11
 
12
+ # Initialize clients
13
+ API_KEY = os.environ.get("HF_API_KEY")
14
+ client = InferenceClient(token=API_KEY)
 
15
 
16
+ def process_file(file):
17
+ """Handle different file types and extract text"""
18
+ if file is None:
19
+ return ""
20
+
21
+ # Get file extension
22
+ ext = file.name.split('.')[-1].lower()
23
+
24
+ try:
25
+ if ext in ['png', 'jpg', 'jpeg']:
26
+ # OCR processing for images
27
+ image = Image.open(file.name)
28
+ text = pytesseract.image_to_string(image)
29
+ return f"IMAGE CONTENT:\n{text}"
30
+
31
+ elif ext == 'pdf':
32
+ # PDF text extraction
33
+ pdf_reader = PyPDF2.PdfReader(file.name)
34
+ text = "\n".join([page.extract_text() for page in pdf_reader.pages])
35
+ return f"PDF CONTENT:\n{text}"
36
+
37
+ elif ext == 'docx':
38
+ # Word document processing
39
+ doc = docx.Document(file.name)
40
+ text = "\n".join([para.text for para in doc.paragraphs])
41
+ return f"DOCUMENT CONTENT:\n{text}"
42
+
43
+ else:
44
+ return "Unsupported file type"
45
+
46
+ except Exception as e:
47
+ print(f"File processing error: {e}")
48
+ return "Error reading file"
49
 
50
+ def chat(message, history, file):
51
+ # Process uploaded file
52
+ file_content = process_file(file) if file else ""
53
+
54
+ # Build enhanced prompt
55
+ full_prompt = f"""
56
+ {file_content}
57
+
58
+ User Message: {message}
59
+
60
+ Please respond considering both the message and any attached documents:"""
61
+
62
+ # Configure generation parameters
63
+ generate_kwargs = dict(
64
+ temperature=0.7,
65
+ max_new_tokens=2000,
66
+ top_p=0.95,
67
+ repetition_penalty=1.2,
68
+ )
69
+
70
+ # Generate response
71
+ stream = client.text_generation(
72
+ full_prompt,
73
  stream=True,
74
+ details=True,
75
+ **generate_kwargs
76
+ )
77
+
78
+ partial_message = ""
79
+ for response in stream:
80
+ if response.token.special:
81
+ continue
82
+ partial_message += response.token.text
83
+ yield partial_message
84
 
85
+ # Create Gradio interface with file upload
86
+ with gr.Blocks(theme="soft") as demo:
87
+ gr.Markdown("# DeepSeek-R1 Assistant with File Support")
88
+ gr.Markdown("Upload images, PDFs, or docs and chat about them!")
89
+
90
+ with gr.Row():
91
+ file_input = gr.File(label="Upload File (PDF/Image/Doc)", type="file")
92
+
93
+ chatbot = gr.ChatInterface(
94
+ fn=chat,
95
+ additional_inputs=[file_input],
96
+ examples=[
97
+ ["Explain this document", "report.pdf"],
98
+ ["What's in this image?", "screenshot.png"]
99
+ ]
100
+ )
101
 
102
+ demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104