sam_ext / app.py
sadickam's picture
Update app.py
52527ff verified
raw
history blame
No virus
13.8 kB
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer
import os
import pandas as pd
from io import StringIO
# Load the API token from environment variable
api_token = os.getenv('HF_API_TOKEN')
# Load the model and tokenizer
model_name = "nvidia/Llama3-ChatQA-1.5-8B"
tokenizer = AutoTokenizer.from_pretrained(model_name, use_auth_token=api_token)
model = AutoModelForCausalLM.from_pretrained(model_name, use_auth_token=api_token)
# Define the few-shot examples
few_shot_examples = """
Extract the aim, main findings, and indicate if the research focus includes roofs in buildings:
Abstract: The present study studies the coupling method of building energy simulation and computational fluid dynamics analysis for the detailed and thorough investigation of roof retrofit techniques. The computations are conducted in DesignBuilder software and concern a one-story residential building, equipped with air-to-air heat pump split units, located in Athens, Greece. The retrofit actions aim at the improvement of the building rooftop thermal and optical properties and include i) the addition of external thermal insulation, ii) the addition of phase change material on the exterior surface, iii) the application of cool coating, and iv) the application of thermochromic coating. The aforementioned techniques are examined as standalone retrofit actions. The yearly heat pump electricity consumption and the local and mean surface thermal comfort indexes of predicted mean vote and predicted percentage of dissatisfied, for a typical winter and summer afternoon hour, are calculated and compared. The importance of the present study lies in the combination of energy simulation and thermal comfort analysis for the multi-criteria assessment and selection of the most suitable roof retrofit technique. Additionally, the evaluation of the indoor thermal environment with the integration of various passive roof retrofit techniques is not adequately investigated in the existing literature. The application of cool roof coating results in the maximum electricity savings for cooling (50.6%), whereas the addition of thermal insulation in the maximum decrease in electricity consumption for heating (21.9%) and total (18.4%). Furthermore, the application of thermochromic roof coating restricts the heating penalty at 6.3% in contrast to the cool coating (42.0%) but increases the predicted percentage of dissatisfied by 170% compared to the baseline scenario, during the examined afternoon winter hour. Lastly, every examined retrofit technique results in a comparable improvement in thermal comfort conditions for summer, undermining the energy advantages of the cool and thermochromic roof coatings, against the energy and thermal comfort effectiveness of the retrofit action of insulation. © 2024 Elsevier B.V.
Aim: “The retrofit actions aim at the improvement of the building rooftop thermal and optical properties and include i) the addition of external thermal insulation, ii) the addition of phase change material on the exterior surface, iii) the application of cool coating, and iv) the application of thermochromic coating.”
Key finding: The application of cool roof coating results in the maximum electricity savings for cooling (50.6%), whereas the addition of thermal insulation in the maximum decrease in electricity consumption for heating (21.9%) and total (18.4%). Furthermore, the application of thermochromic roof coating restricts the heating penalty at 6.3% in contrast to the cool coating (42.0%) but increases the predicted percentage of dissatisfied by 170% compared to the baseline scenario, during the examined afternoon winter hour.
Focus includes roofs in buildings: Yes
Abstract: The building envelope with its different components (Windows, roofs, walls, slabs on grade) is one of the main building elements that has a significant impact on the building’s energy efficiency. To improve the building’s energy efficiency and better control the desired interior temperature, in both cold and hot climates, architects and engineers principally act to hinder the undesired heat flow from within the building to the outside and from outside the building to the inside in order to achieve the desired thermal comfort for the building’s occupants. Hence, this paper focuses on one of the most constructional passive elements in the building envelope, namely the external wall. For that reason, a series of calculations are executed to numerically assess the thermal resistance values (R-values) and the thermal transmittance values (U-values) of some external wall ensembles used mainly in common residential building construction practices in Lebanon. The improvement of the thermal insulation is made by adding a 4 cm thick extruded polystyrene board mounted with a 2.5 mm thick polypropylene mesh upon which a 12.5 mm thick plaster layer is applied. The thermal transmittance was reduced by 75%. © 2024 by authors, all rights reserved.
Aim: “Hence, this paper focuses on one of the most constructional passive elements in the building envelope, namely the external wall. For that reason, a series of calculations are executed to numerically assess the thermal resistance values (R-values) and the thermal transmittance values (U-values) of some external wall ensembles used mainly in common residential building construction practices in Lebanon.’
Key findings: “The improvement of the thermal insulation is made by adding a 4 cm thick extruded polystyrene board mounted with a 2.5 mm thick polypropylene mesh upon which a 12.5 mm thick plaster layer is applied. The thermal transmittance was reduced by 75%.”
Focus includes roofs in buildings: No
Abstract: Solar thermal energy usage in the Baltic countries is currently low, so there is a need to find technically and economically feasible solutions to increase the appeal of this technology. Integration of solar energy into existing district heating systems is a way to increase the share of renewable energy sources while utilizing the existing infrastructure, thereby reducing capital investments, as well as mitigating the risk of solar collector overheating and eliminating the need for local storage tanks in buildings. This study presents a parametric study for evaluating the effectiveness of using a district heating system to store heat produced by decentralized solar thermal collectors and comparing the district solution to the traditional local solution. The TRNSYS 18 model was developed for this purpose. The model investigates the impact of different hot tap water demand profiles as well as pipeline diameters and lengths on system energy efficiency, showing a statistically significant difference (p < 0.05) between installing solar collectors on residential and restaurant or office roofs, and no significant difference (p = 0.24) between restaurant and office. The model shows that solar energy can be shared within a 500 m distance between neighborhoods and that a larger main pipeline diameter can increase overall system efficiency. © 2024 Elsevier Ltd
Aim: “This study presents a parametric study for evaluating the effectiveness of using a district heating system to store heat produced by decentralized solar thermal collectors and comparing the district solution to the traditional local solution.”
Key findings: “The model shows that solar energy can be shared within a 500 m distance between neighborhoods and that a larger main pipeline diameter can increase overall system efficiency.”
Focus includes roofs in buildings: No
Abstract: Retrofitting residential buildings could substantially reduce the sector's energy and carbon footprint and provide significant economic benefits in the long run. Building retrofits must be urgently developed and promoted in India, where most residences are constructed without any consideration of energy efficiency due to the lack of a mandatory residential energy code. However, building retrofits must be devised considering the local construction practices and climatic conditions since an improper retrofit can deteriorate the indoor environment and even increase the building's energy consumption. Therefore, through year-long monitoring and simulations of the comfort conditions of a room inside a detached single-story house, this investigation evaluated different envelope retrofit options for improving it in India's hot semi-arid climate. The results showed that the room's indoor environment (without the retrofit) was comfortable for only 26–43 % of the year, depending on the room's configuration, with the roof being the major contributor to the heat gain and the floor and external walls largely contributing to heat losses. The comfort duration increased by 6–21 percentage points annually by applying cool/super-cool roof paints since they significantly reduce the roof's heat gain. Similar comfort enhancements could also be obtained by insulating the roof or the entire envelope, mainly due to reduced roof heat gains. However, insulating the walls alone deteriorated the comfort conditions since it became difficult for the heat to escape the room. Overall, applying cool/super-cool roof paints was recommended over other studied options since they provide substantial comfort benefits with low cost and easy implementation. © 2024 Elsevier Ltd
Aim: “Therefore, through year-long monitoring and simulations of the comfort conditions of a room inside a detached single-story house, this investigation evaluated different envelope retrofit options for improving it in India's hot semi-arid climate.”
Key findings: “The results showed that the room's indoor environment (without the retrofit) was comfortable for only 26–43 % of the year, depending on the room's configuration, with the roof being the major contributor to the heat gain and the floor and external walls largely contributing to heat losses. The comfort duration increased by 6–21 percentage points annually by applying cool/super-cool roof paints since they significantly reduce the roof's heat gain.”
Focus includes roofs in buildings: Yes
"""
# Define the system instructions
system_instructions = """
You are an intelligent system that extracts key information from academic abstracts. Use the given examples to understand the format and extract the aim, main findings, and indication if the research focus include roofs in buildings. This decision is based on the stated aim and objectives or if results are explicitly reported for roofs. This would be "No" if the research extrapolates implications for roofs without reporting research results for roofs.
"""
# Function to extract information from a given text
def extract_information(text):
# Combine the system instructions, few-shot examples, and the text
prompt = system_instructions + few_shot_examples + f"\n\nText: {text}\nAim:\nMain Findings:\nFocus on Roofs (Yes/No):"
# Tokenize the input
inputs = tokenizer(prompt, return_tensors="pt")
# Generate a response
output_sequences = model.generate(
input_ids=inputs['input_ids'],
max_length=200, # Adjust based on your needs
temperature=0.7, # Control the randomness of the output
top_k=0,
top_p=1,
repetition_penalty=1.0, # Penalty for repeating the same words
num_return_sequences=1 # Generate a single sequence
)
# Decode the generated text
generated_text = tokenizer.decode(output_sequences[0], skip_special_tokens=True)
# Extract the aim, main findings, and focus on roofs (Yes/No) from the generated text
aim_start = generated_text.find("Aim:") + len("Aim:")
main_findings_start = generated_text.find("Main Findings:") + len("Main Findings:")
focus_on_roofs_start = generated_text.find("Focus on Roofs (Yes/No):") + len("Focus on Roofs (Yes/No):")
aim = generated_text[aim_start:main_findings_start].strip()
main_findings = generated_text[main_findings_start:focus_on_roofs_start].strip()
focus_on_roofs = generated_text[focus_on_roofs_start:].strip()
return aim, main_findings, focus_on_roofs
# Function to process CSV file and extract information
def process_csv(file, column_name):
# Load CSV into a DataFrame
df = pd.read_csv(file)
# Extract text from specified column
texts = df[column_name].tolist()
# Extract information for each text
extracted_results = []
for text in texts:
aim, main_findings, focus_on_roofs = extract_information(text)
extracted_results.append((aim, main_findings, focus_on_roofs))
# Add extracted information to the original DataFrame
df['Aim'] = [result[0] for result in extracted_results]
df['Main Findings'] = [result[1] for result in extracted_results]
df['Focus on Roofs'] = [result[2] for result in extracted_results]
return df
# Create the Gradio interface
input_file = gr.inputs.File(label="Upload CSV File")
input_column = gr.inputs.Textbox(label="Column Name", placeholder="Enter column name containing text")
output_text = gr.outputs.Textbox(label="Status")
# Define Gradio app interface function
def gradio_interface(file, column_name):
df = process_csv(file, column_name)
# Save the DataFrame to a CSV string
csv_string = df.to_csv(index=False)
return csv_string
# Launch the Gradio app
gr.Interface(
fn=gradio_interface,
inputs=[input_file, input_column],
outputs=output_text,
title="Research Information Extraction",
description="Upload a CSV file and specify the column containing the text to extract aim, main findings, and focus on roofs in buildings. Returns a downloadable CSV with extracted information."
).launch()