Engr-Saeed commited on
Commit
5932572
1 Parent(s): f1f896a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -62
app.py CHANGED
@@ -1,63 +1,89 @@
 
 
 
 
 
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
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
- )
60
-
61
-
62
- if __name__ == "__main__":
63
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from PyPDF2 import PdfReader
3
+ from docx import Document
4
+ import os
5
+ from groq import Groq
6
  import gradio as gr
7
+
8
+ # Function to read and process different document types
9
+ def read_document(file):
10
+ try:
11
+ file_extension = os.path.splitext(file.name)[-1].lower()
12
+ print(f"Processing file: {file.name} with extension {file_extension}")
13
+
14
+ if file_extension == '.txt':
15
+ return file.read().decode('utf-8')
16
+ elif file_extension == '.pdf':
17
+ reader = PdfReader(file)
18
+ text = ''
19
+ for page in reader.pages:
20
+ text += page.extract_text()
21
+ return text
22
+ elif file_extension == '.docx':
23
+ doc = Document(file)
24
+ return '\n'.join([paragraph.text for paragraph in doc.paragraphs])
25
+ elif file_extension in ['.csv', '.xls', '.xlsx']:
26
+ df = pd.read_excel(file) if file_extension != '.csv' else pd.read_csv(file)
27
+ return df.to_string(index=False)
28
+ else:
29
+ return "Unsupported file format"
30
+ except Exception as e:
31
+ print(f"Error processing file: {file.name} - {str(e)}")
32
+ return f"Error processing file: {file.name} - {str(e)}"
33
+
34
+ # Set your API key as an environment variable
35
+ GROQ_API_KEY = "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" # Replace with your actual API key
36
+
37
+ client = Groq()
38
+
39
+ # Function to validate and truncate content to prevent API errors
40
+ def validate_content(text):
41
+ # Basic validation to remove unwanted characters
42
+ validated_text = ''.join(e for e in text if e.isalnum() or e.isspace())
43
+ # Truncate text if it's too long
44
+ max_length = 8000 # Adjust as needed
45
+ if len(validated_text) > max_length:
46
+ validated_text = validated_text[:max_length] + "..."
47
+ return validated_text
48
+
49
+ # Function to get an answer from the Groq API
50
+ def get_answer(question, model="llama3-8b-8192"):
51
+ try:
52
+ chat_completion = client.chat.completions.create(
53
+ model=model,
54
+ messages=[{"role": "user", "content": question}],
55
+ )
56
+ return chat_completion.choices[0].message.content
57
+ except Exception as e:
58
+ print(f"Error in Groq API call: {str(e)}")
59
+ if hasattr(e, 'response'):
60
+ print(f"Full response: {e.response.json()}")
61
+ return f"Error in API call: {str(e)}"
62
+
63
+ # Function to interface with the Gradio UI
64
+ def chatbot_interface(documents, question):
65
+ text = ''
66
+ for doc in documents:
67
+ content = read_document(doc)
68
+ text += validate_content(content) + "\n\n"
69
+
70
+ answer = get_answer(f"{text}\n\nQuestion: {question}")
71
+ return answer
72
+
73
+ # Gradio Interface
74
+ with gr.Blocks(theme=gr.themes.Default(primary_hue="slate")) as demo:
75
+ gr.Markdown("# RAG-based Q/A Chatbot with Document Support", elem_id="title")
76
+ gr.Markdown("Upload documents and ask questions related to them.", elem_id="description")
77
+
78
+ with gr.Row():
79
+ with gr.Column():
80
+ doc_input = gr.File(file_count="multiple", label="Upload Documents")
81
+ question_input = gr.Textbox(label="Ask a Question")
82
+
83
+ with gr.Column():
84
+ output = gr.Textbox(label="Answer")
85
+
86
+ submit_button = gr.Button("Get Answer")
87
+ submit_button.click(chatbot_interface, inputs=[doc_input, question_input], outputs=output)
88
+
89
+ demo.launch()