Create app.py
Browse files
app.py
CHANGED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
from transformers import pipeline
|
| 3 |
+
from sentence_transformers import SentenceTransformer
|
| 4 |
+
import faiss
|
| 5 |
+
import numpy as np
|
| 6 |
+
import gradio as gr
|
| 7 |
+
|
| 8 |
+
# Initialize a free question-answering model from Hugging Face
|
| 9 |
+
question_answerer = pipeline("question-answering", model="distilbert-base-cased-distilled-squad")
|
| 10 |
+
|
| 11 |
+
# Load or create data on economic and population growth trends
|
| 12 |
+
documents = [
|
| 13 |
+
{"id": 1, "text": "Global economic growth is projected to slow down due to inflation."},
|
| 14 |
+
{"id": 2, "text": "Population growth in developing countries continues to increase."},
|
| 15 |
+
{"id": 3, "text": "Economic growth in advanced economies is experiencing fluctuations due to market changes."},
|
| 16 |
+
# Add more documents as needed
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
# Embed documents for retrieval using SentenceTransformer
|
| 20 |
+
embedder = SentenceTransformer('all-MiniLM-L6-v2') # A lightweight embedding model
|
| 21 |
+
document_embeddings = [embedder.encode(doc['text']) for doc in documents]
|
| 22 |
+
|
| 23 |
+
# Convert embeddings to a FAISS index for similarity search
|
| 24 |
+
index = faiss.IndexFlatL2(384) # Dimension of the embeddings
|
| 25 |
+
index.add(np.array(document_embeddings))
|
| 26 |
+
|
| 27 |
+
# Define the RAG retrieval function
|
| 28 |
+
def retrieve_documents(query, top_k=3):
|
| 29 |
+
query_embedding = embedder.encode(query).reshape(1, -1)
|
| 30 |
+
distances, indices = index.search(query_embedding, top_k)
|
| 31 |
+
return [documents[i]['text'] for i in indices[0]]
|
| 32 |
+
|
| 33 |
+
# Implement the question-answering function with retrieval
|
| 34 |
+
def ask_question(question):
|
| 35 |
+
retrieved_docs = retrieve_documents(question)
|
| 36 |
+
context = " ".join(retrieved_docs)
|
| 37 |
+
answer = question_answerer(question=question, context=context)
|
| 38 |
+
return answer['answer']
|
| 39 |
+
|
| 40 |
+
# Create Gradio Interface for the RAG app
|
| 41 |
+
def rag_interface(question):
|
| 42 |
+
answer = ask_question(question)
|
| 43 |
+
return answer
|
| 44 |
+
|
| 45 |
+
interface = gr.Interface(
|
| 46 |
+
fn=rag_interface,
|
| 47 |
+
inputs="text",
|
| 48 |
+
outputs="text",
|
| 49 |
+
title="Economic and Population Growth Advisor",
|
| 50 |
+
description="Ask questions related to economic and population growth. This app uses retrieval-augmented generation to provide answers based on relevant documents."
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
interface.launch(debug=True)
|